JSON 模式 OneOf 级联

标签 json jsonschema

我问自己的是,我是否可以级联多个“oneOf”,或者也许有更好的方法来使我的案例有效。

我正在尝试验证以下内容:

使用 ObjectA 或 ObjectB 的定义作为单个对象或它们的数组

情况1:

仅使用 ObjectA 的定义

{
 "X": "test"
}

情况2:

仅使用ObjectB的定义

{
 "Y": "test"
}

情况3:

在数组中使用 ObjectA 或 ObjectB 的定义

[
 {
  "X": "test"
 },
 {
  "Y": "test"
 }
]

情况 4:

在数组中使用 ObjectA 的定义两次

[
 {
  "X": "test"
 },
 {
  "X": "test"
 }
]

架构:

我尝试使用此架构,MonacoEditor 的 IntelliSense 运行良好,但我仍然收到错误/警告:“当只有一个必须验证时,匹配多个架构。”

{
 "definitions": {
  "objectA": {
  "type": "object",
  "properties": {
   "X": {
    type: "string"
   }
  }
 },
  "objectB": {
   "type": "object",
   "properties": {
    "Y": {
     type: "string"
    }
   }
  }
 },
 "oneOf":
  [
   {
    "oneOf":
     [
      {
       "$ref": "#definitions/objectA"
      },
      {
       "$ref": "#definitions/objectB"
      }
     ]
    },
    {
     "type": "array",
     "items": 
      {
       "oneOf":
        [
         {
          "$ref": "#definitions/objectA"
         },
         {
          "$ref": "#definitions/objectB"
         }
        ]        
      }
    }
  ]
}

错误/警告:

“当只有一个模式必须验证时,匹配多个模式。”

最佳答案

问题是 objectA 中的 X 属性和 objectB 中的 Y 属性不是必需的,因此空对象(即 { })会针对这两个属性进行验证。

此外,如果您希望包含 objectA 和 objectY 的数组有效,则需要使用 anyOf 而不是 oneOf。

{
 "definitions": {
   "objectA": {
     "type": "object",
     "properties": {
       "X": {
         "type": "string"
       }
     },
     "required": ["X"]
   },
   "objectB": {
     "type": "object",
     "properties": {
       "Y": {
         "type": "string"
       }
     },
     "required": ["Y"]
   }
 },
 "oneOf":
  [
   {"$ref": "#/definitions/objectA"},
   {"$ref": "#/definitions/objectB"},
   {
     "type": "array",
     "minItems": 1,
     "items":
     {
       "anyOf":
       [
         {"$ref": "#/definitions/objectA"},
         {"$ref": "#/definitions/objectB"}
       ]        
     }
   }
  ]
}

如果您不想验证空数组,我添加了 minItems。

关于JSON 模式 OneOf 级联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56112003/

相关文章:

json - 使用 GSON 使用通用嵌套数据对象序列化响应对象

arrays - 获取 JSON 数据以从数组填充 TableView

java - Angular、JSON map 数据不会转换为 map

json - 在 JsonSchema 中,格式值应设置为 "full-date"或 "date"?

java - XML 到 JSON 的转换 : empty array instead of empty string

javascript - 从 Json 数据异步加载 Google map 标记

javascript - 从 JSON Schema 模型派生 JSON 路径列表

jsonschema - 覆盖继承的 json 模式

arrays - 如何在 json 模式中定义数组的最小大小

json - 有谁知道开源 JSON 模式元数据存储库?