在 JSON 模式中,当属性引用另一个定义的模式时,为了保留引用定义的类型,最好将引用定义包装在“allOf”中并在引用定义之外的该定义中指示属性类型吗?还是在引用的定义中指示属性类型而不使用“allOf”更好?
例如,在下面的第一个模式中,mainObject 和 objectA 的属性引用都包含在“allOf”中,并且在 mainObject 和 objectA 属性中具有“type”:“object”。而在模式版本 2 中,“mainObject”和“objectAInfo”定义指示“对象”的“类型”。
从我在测试中看到的情况来看,这两个都实现了相同的验证目标,所以我想知道是否有特别的理由使用模式版本 1 而不是模式版本 2?
架构版本 1:
{
"info": {
"title": "mainObject",
"version": "0.0.1",
"baseUri": "",
"description": "An example object schema"
},
"properties": {
"mainObject": {
"type": "object",
"allOf": [
{
"$ref": "#/definitions/mainObject"
}
]
}
},
"required": [],
"definitions": {
"mainObject": {
"additionalProperties": false,
"description": "The financials entity root.",
"required": [],
"properties": {
"objectA": {
"type": "object",
"description": "Information on the liability accrued by the taxpayer",
"allOf": [
{
"$ref": "#/definitions/objectAInfo"
}
]
}
}
},
"objectAInfo": {
"additionalProperties": false,
"required": [],
"properties": {
"total1": {
"type": "number",
"description": "Overall liability accrued during the tax period. This number does not go down as the taxpayer pays off their liability. That is reflected in the periodBalance."
},
"total2": {
"type": "number",
"description": "Overall liability accrued during the tax period. This number does not go down as the taxpayer pays off their liability. That is reflected in the periodBalance."
}
}
}
},
"$schema": "http://json-schema.org/draft-07/schema#",
"lang": "zxx",
"$id": "http://example.com/"
}
架构版本 2:
{
"info": {
"title": "mainObject",
"version": "0.0.1",
"baseUri": "",
"description": "An example object schema"
},
"properties": {
"mainObject": {
"$ref": "#/definitions/mainObject"
}
},
"required": [],
"definitions": {
"mainObject": {
"type": "object",
"additionalProperties": false,
"description": "The financials entity root.",
"required": [],
"properties": {
"objectA": {
"$ref": "#/definitions/objectAInfo"
}
}
},
"objectAInfo": {
"type": "object",
"additionalProperties": false,
"required": [],
"properties": {
"total1": {
"type": "number",
"description": "Overall liability accrued during the tax period. This number does not go down as the taxpayer pays off their liability. That is reflected in the periodBalance."
},
"total2": {
"type": "number",
"description": "Overall liability accrued during the tax period. This number does not go down as the taxpayer pays off their liability. That is reflected in the periodBalance."
}
}
}
},
"$schema": "http://json-schema.org/draft-07/schema#",
"lang": "zxx",
"$id": "http://example.com/"
}
要验证的示例文档:
{
"mainObject": {
"objectA": {
"total1": 0,
"total2": 1
}
}
}
这取决于三件事:
$ref
本身,这意味着如果您有其他约束(例如,您的 Schema 1 中的 type
),它们将被忽略。但是,在 2019-09 及以后的草案中,$ref
可以有同级关键字(type
也会被验证)。allOf
中的单独子模式中。否则你会有重复的$ref
键。简短的回答:对于现代模式实现,这取决于你。请确保您使用
$schema
. 声明您使用的是哪个版本