JSON 架构:合并多个引用

JSON Schema: Combine multiple references

我的Json架构

{
  "$schema": "http://json-schema.org/draft-07/schema#",
    
  "definitions": {
    
    "userInfo": {
      "type": "object",
      "properties": {
        "firstName": { "type": "string" },
        "lastName":  { "type": "string" },
        "emailAddress":{ "type": "string" }
      },
      "required": ["firstName", "lastName", "emailAddress"]
    },
    
    "userPassword": {
      "type": "object",
      "properties": {
        "password": { "type": "string" },
        "confirmPassword":  { "type": "string" }
      }
    }
  },

  "type": "object",
    
  "properties": {
    "standaloneDeveloper": {
      "$ref": "#/definitions/userInfo",
      "$ref": "#/definitions/userPassword"
    } 
  }
}

数据总是被#/definitions/userPassword

覆盖

我使用此架构得到以下输出

{
  "standaloneDeveloper": {
    "password": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC",
    "confirmPassword": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC"
  }
}

预期输出

{
  "standaloneDeveloper": {
    "firstName": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC",
    "lastName": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC",
    "emailAddress": "ABCDEFGHI",
    "password": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC",
    "confirmPassword": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC"
  }
}

如何合并 userInfo 和 userPassword?

在 JSON 中(因此 JSON 模式也是如此)您不能有重复的 属性 名称。您可以使用 allOf 来解决这个问题。

"properties": {
  "standaloneDeveloper": {
    "allOf": [
      { "$ref": "#/definitions/userInfo" },
      { "$ref": "#/definitions/userPassword" }
    ]
  }
}

这样每个对象里面只有一个$ref