我问自己的是,我是否可以级联多个“oneOf”,或者也许有更好的方法来使我的案例有效。
我正在尝试验证以下内容:
使用 ObjectA 或 ObjectB 的定义作为单个对象或它们的数组
情况1:
仅使用 ObjectA 的定义
{
"X": "test"
}
情况2:
仅使用ObjectB的定义
{
"Y": "test"
}
情况3:
在数组中使用 ObjectA 或 ObjectB 的定义
[
{
"X": "test"
},
{
"Y": "test"
}
]
情况 4:
在数组中使用 ObjectA 的定义两次
[
{
"X": "test"
},
{
"X": "test"
}
]
架构:
我尝试使用此架构,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"
}
]
}
}
]
}
错误/警告:
“当只有一个模式必须验证时,匹配多个模式。”
最佳答案
问题是 objectA 中的 X 属性和 objectB 中的 Y 属性不是必需的,因此空对象(即 { })会针对这两个属性进行验证。
此外,如果您希望包含 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"}
]
}
}
]
}
如果您不想验证空数组,我添加了 minItems。
关于JSON 模式 OneOf 级联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56112003/