[英]What is the difference between “anyof” and “oneof” in z schema?
看起来两者都适用于我的输入验证代码。 那究竟是什么区别?
具有oneof的架构
[{
"id": "MyAction",
"oneOf": [{ "$ref": "A1" },
{ "$ref": "A2" }]
},
{
"id": "A1",
"properties": {
"class1": { "type": "string"},
"class2": { "type": "string"}
}
},
{
"id": "A2",
"properties": {
"class2": { "type": "string"},
"class3": { "type": "string"}
}
}
]
架构与任何
[{
"id": "MyAction",
"anyOf": [{ "$ref": "A1" },
{ "$ref": "A2" }]
},
{
"id": "A1",
"properties": {
"class1": { "type": "string"},
"class2": { "type": "string"}
}
},
{
"id": "A2",
"properties": {
"class2": { "type": "string"},
"class3": { "type": "string"}
}
}
]
如果您查看JSON Schema文档 ,它会说:
5.5.4。 任何
5.5.4.1。 有效值
该关键字的值必须是一个数组。 这个数组必须至少有一个元素。
数组的元素必须是对象。 每个对象必须是有效的JSON模式。
5.5.4.2。 成功验证的条件
如果实例针对此关键字的值定义的至少一个模式成功验证,则实例将针对此关键字成功验证。
5.5.5。 oneOf
5.5.5.1。 有效值
该关键字的值必须是一个数组。 这个数组必须至少有一个元素。
数组的元素必须是对象。 每个对象必须是有效的JSON模式。
5.5.5.2。 成功验证的条件
如果实例针对此关键字的值定义的一个模式成功验证,则实例将针对此关键字成功验证。
请注意我在上面的重点。 anyOf
表示该项必须针对至少一个(但可能不止一个 )模式进行验证。 oneOf
意味着它必须只针对其中一个模式进行验证。
我在这个任务中迟到了,但根据我的理解,这个关键字的用法取决于对象/父本身的类型。 例如,如果您尝试为对象的单个属性或数组的元素定义类型。 采取以下示例:
{
"title": "Sample JSON Schema",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"definitions": {
"propObjectType1" : {
"name": "string",
"age": "number"
},
"propObjectType2" : {
"name": "string",
"dob": {
"type": "string",
"pattern": "\\d\\d\/\\d\\d\/\\d\\d\\d\\d"
}
}
},
"properties": {
"prop1": {
"type": "string",
"maxLength": 64
},
"prop2": {
"anyOf": [
{
"$ref": "#/definitions/propObjectType1"
},
{
"$ref": "#/definitions/propObjectType2"
}
]
},
"prop3": {
"oneOf": [
{
"$ref": "#/definitions/propObjectType1"
},
{
"$ref": "#/definitions/propObjectType2"
}
]
},
"prop4Array": {
"type": "array",
"items": {
"oneOf": [
{
"$ref": "#/definitions/propObjectType1"
},
{
"$ref": "#/definitions/propObjectType2"
}
]
}
},
"prop5Array": {
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/propObjectType1"
},
{
"$ref": "#/definitions/propObjectType2"
}
]
}
}
}
}
所以在上面的定义中,prop2和prop3是相同的(你可以互换使用anyOf
或oneOf
),你可以定义你感觉舒服的东西。 但是,如果是数组:
anyOf
作为项类型时,元素可以是其中的任何类型,并且数组可以包含混合项。 意味着您可以拥有一个类型1的项目和另一个类型为2的项目。 oneOf
作为项类型时,元素可以是其中的任何类型,并且数组只能包含一种类型的项。 表示所有项目必须属于同一类型(类型1或类型2)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.