JSON schema - how to use oneOf

此生再无相见时 提交于 2019-12-11 02:49:12

问题


The following is a valid JSON schema according to http://jsonlint.com/ and http://jsonschemalint.com/draft4/#.

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "required": ["results"],
    "additionalProperties": false,
    "properties": {
        "results": {
            "type": "string",
            "oneOf": [
                { "result": "1" },
                { "result": "2" },
                { "result": "3" },
                { "result": "4" }
            ]
        }
    }
}

The following JSON reports an error (results is the wrong type) when validated against the above schema:

{
    "results" : {
        "result": "1"
    }
}

Can anyone suggest how I might resolve this error?


回答1:


It looks like what you want in this case is enum rather than oneOf. Here is how you would define your schema.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["results"],
  "additionalProperties": false,
  "properties": {
    "results": {
      "type": "object",
      "properties": {
        "result": {
          "type": "string",
          "enum": ["1", "2", "3", "4"]
        }
      }
    }
  }
}

But, the question was how to use oneOf properly. The oneOf keyword should be an array of schemas, not values as you have used in your example. One and only one of the schemas in oneOf must validate against the data for the oneOf clause to validate. I have to modify your example a little to illustrate how to use oneOf. This example allows result to be a string or an integer.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["results"],
  "additionalProperties": false,
  "properties": {
    "results": {
      "type": "object",
      "properties": {
        "result": {
          "oneOf": [
            {
              "type": "string",
              "enum": ["1", "2", "3", "4"]
            },
            {
              "type": "integer",
              "minimum": 1,
              "maximum": 4
            }
          ]
        }
      }
    }
  }
}



回答2:


results is a type of object as per you schema definition but you mentioned type as String. If I change the type as object, It just works fine.



来源:https://stackoverflow.com/questions/30298740/json-schema-how-to-use-oneof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!