简体   繁体   English

JSON模式级联

[英]JSON Schema OneOf Cascading

What I am asking myself is if I can cascade multiple 'oneOf' or maybe there is a better way to make my Cases Valid. 我想问自己的问题是,我是否可以级联多个“ oneOf”,或者有更好的方法来使我的案例有效。

I am Trying to validate the following: 我正在尝试验证以下内容:

Use definition of ObjectA or ObjectB as Single Objects or an Array of a them 使用ObjectA或ObjectB的定义作为单个对象或它们的数组

Case 1: 情况1:

Using only definition of ObjectA 仅使用ObjectA的定义

{
 "X": "test"
}

Case 2: 情况2:

Using only definition of ObjectB 仅使用ObjectB的定义

{
 "Y": "test"
}

Case 3: 情况3:

Using definition of ObjectA or ObjectB in an Array 在数组中使用ObjectA或ObjectB的定义

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

Case 4: 情况4:

Using definition of ObjectA twice in an Array 在数组中两次使用ObjectA的定义

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

Schema: 架构:

I tryed using this schema, the IntelliSense of MonacoEditor is working well but I still get the Error/Warning: "Matches multiple schemas when only one must validate." 我尝试使用此架构,但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"
         }
        ]        
      }
    }
  ]
}

Error/Warning: 错误/警告:

"Matches multiple schemas when only one must validate." “只有一个必须验证时,才匹配多个模式。”

The problem is that your X property in objectA and Y property en objectB are not required, so an empty object, that is { }, validates against both. 问题在于您不需要objectA中的X属性和objectB中的Y属性,因此,一个空对象(即{)可以同时验证这两个对象。

Also, if you want an array with objectA and objectY to be valid, you need to use anyOf instead of oneOf. 另外,如果希望具有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"}
       ]        
     }
   }
  ]
}

I added the minItems if you don't want an empty array to validate. 如果您不想验证空数组,则添加了minItems。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM