oneOf对象的Json架构示例

jm81lzqq  于 2023-02-20  发布在  其他
关注(0)|答案(2)|浏览(106)

我试图通过建立一个验证两种不同对象类型的模式来弄清楚oneOf是如何工作的。例如,一个人(名、姓、运动)和车辆(类型、成本)。
以下是一些示例对象:

{"firstName":"John", "lastName":"Doe", "sport": "football"}

{"vehicle":"car", "price":20000}

问题是我做错了什么,我该如何改正。

{
    "description": "schema validating people and vehicles", 
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "required": [ "oneOf" ],
    "properties": { "oneOf": [
        {
            "firstName": {"type": "string"}, 
            "lastName": {"type": "string"}, 
            "sport": {"type": "string"}
        }, 
        {
            "vehicle": {"type": "string"}, 
            "price":{"type": "integer"} 
        }
     ]
   }
}

当我尝试在这个解析器中验证它时:

https://json-schema-validator.herokuapp.com/

出现以下错误:

[ {
  "level" : "fatal",
  "message" : "invalid JSON Schema, cannot continue\nSyntax errors:\n[ {\n  \"level\" : \"error\",\n  \"schema\" : {\n    \"loadingURI\" : \"#\",\n    \"pointer\" : \"/properties/oneOf\"\n  },\n  \"domain\" : \"syntax\",\n  \"message\" : \"JSON value is of type array, not a JSON Schema (expected an object)\",\n  \"found\" : \"array\"\n} ]",
  "info" : "other messages follow (if any)"
}, {
  "level" : "error",
  "schema" : {
    "loadingURI" : "#",
    "pointer" : "/properties/oneOf"
  },
  "domain" : "syntax",
  "message" : "JSON value is of type array, not a JSON Schema (expected an object)",
  "found" : "array"
} ]
omtl5h9j

omtl5h9j1#

试试这个:

{
    "description" : "schema validating people and vehicles",
    "type" : "object",
    "oneOf" : [
       {
        "type" : "object",
        "properties" : {
            "firstName" : {
                "type" : "string"
            },
            "lastName" : {
                "type" : "string"
            },
            "sport" : {
                "type" : "string"
            }
          }
      }, 
      {
        "type" : "object",
        "properties" : {
            "vehicle" : {
                "type" : "string"
            },
            "price" : {
                "type" : "integer"
            }
        },
        "additionalProperties":false
     }
]
}
jgwigjjp

jgwigjjp2#

oneOf需要在模式中使用才能工作。

properties中,它就像另一个名为“oneOf”的属性,没有您想要的效果。

相关问题