问题描述
如何设置JSON Schema规则以说必须要设置并确实是其中一个属性?
How to set JSON Schema rule to say that exactly one of the properties have to be set and is required?
我尝试了多种解决方法,例如:
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"
}
}
}
但是它从来没有奏效.我需要做的就是接受station_id是一个整数,或者接受station是一个字符串名.
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.
请问有办法吗?
推荐答案
oneOf
仅在直接在架构内使用时才特殊.在properties
中使用oneOf
时,它没有特殊含义,因此实际上您最终定义了一个名为"oneOf"
的属性.
oneOf
is only special when used directly inside a schema. When you use oneOf
inside properties
, then it has no special meaning, so you actually end up defining a property called "oneOf"
instead.
此外-并不是必需的属性定义,而是required
关键字.此关键字是必需属性的数组(不是布尔值,这是旧语法).
Also - it's not the property definitions that make something required, it's the required
keyword. This keyword is an array of required properties (not a boolean, that's old syntax).
要执行所需的操作,请创建一个oneOf
子句,其中一个选项需要"station_id"
,而另一个选项需要"station"
:
To do what you want, you make a oneOf
clause where one option has "station_id"
required, and the other has "station"
required:
{
"oneOf": [
{"required": ["station"]},
{"required": ["station_id"]}
]
}
如果同时存在和,则数据将无效(因为仅允许通过一个oneOf
条目).
If both are present, then the data will be invalid (because only one oneOf
entry is allowed to pass).
这篇关于JSON模式oneOf属性已填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!