简体   繁体   English

JSON Schema oneOf特色填充

[英]JSON Schema oneOf properies filled

How to set JSON Schema rule to say that exactly one of the properties have to be set and is required? 如何设置JSON Schema规则以确定必须设置其中一个属性并且是必需的?

I tried various ways to solve it like: 我尝试了各种方法来解决它:

{
   "id":"#",
   "required":true,
   "additionalProperties":true,
   "type":"object",
   "properties":{
      "surname":{
         "id":"surname",
         "required":true,
         "type":"string"
      },
      "oneOf":[
         {
            "$ref":"#/definitions/station_id"
         },
         {
            "$ref":"#/definitions/station"
         }
      ]
   },
   "definitions":{
      "station_id":{
         "type":"integer"
      },
      "station":{
         "type":"string"
      }
   }
}

But it never worked. 但它从来没有奏效。 What I need to do is to accept either station_id what is an integer or station what is a string name. 我需要做的是接受station_id什么是整数或者什么是字符串名称。

Is there a way to do that, please? 请问有办法吗?

oneOf is only special when used directly inside a schema. oneOf仅在模式中直接使用时才是特殊的。 When you use oneOf inside properties , then it has no special meaning, so you actually end up defining a property called "oneOf" instead. 当你在内部properties使用oneOf ,它没有特殊含义,所以你实际上最终定义了一个名为"oneOf"的属性。

Also - it's not the property definitions that make something required, it's the required keyword. 此外 - 不是必需的属性定义,它是required关键字。 This keyword is an array of required properties (not a boolean, that's old syntax). 此关键字是必需属性的数组(不是布尔值,即旧语法)。

To do what you want, you make a oneOf clause where one option has "station_id" required, and the other has "station" required: 要做你想做的事,你做一个oneOf子句,其中一个选项需要"station_id" oneOf ,另一个选项需要"station"

{
    "oneOf": [
        {"required": ["station"]},
        {"required": ["station_id"]}
    ]
}

If both are present, then the data will be invalid (because only one oneOf entry is allowed to pass). 如果两者都存在,则该数据将被无效(因为只有一个oneOf条目被允许通过)。

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

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