【发布时间】:2019-07-02 12:03:14
【问题描述】:
我的 JSON 有效负载包含两个属性 home_number、home_name 和始终需要至少一个属性。除此之外,这些属性还有以下附加限制。
home_number:类型:字符串,最大长度:4
home_name:类型:字符串,最大长度:50
如果两个属性都不满足要求,JSON 模式应该抛出一个错误。
例如:
有效的 JSON
{
"home_number": "1234", // valid
}
有效的 JSON
{
"home_number": null, // invalid
"home_name": "test_home_name" // valid
}
无效的 JSON
{
"home_number": "12345", // invalid
"home_name": null // invalid
}
我使用 if, then 关键字尝试了以下带有 draft-07 版本的 JSON 架构。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"address": {
"$ref": "#/definitions/address",
"properties": {
"house_number": {
"$ref": "#/definitions/address/house_number"
},
"house_name": {
"$ref": "#/definitions/address/house_name"
},
"post_code": {
"$ref": "#/definitions/address/postcode"
}
}
}
},
"required": [
"address"
],
"definitions": {
"address": {
"type": "object",
"properties": {
"postcode": {
"type": "string",
"maxLength": 6
}
},
"anyOf": [
{
"required": [
"house_number"
]
},
{
"required": [
"house_name"
]
}
],
"if": {
"properties": {
"house_name": {
"not": {
"type": "string",
"maxLength": 50
}
}
}
},
"then": {
"properties": {
"house_number": {
"type": "string",
"maxLength": 4
}
}
},
"required": [
"postcode"
]
}
}
}
我的问题是有没有其他/更好的方法来实现这一点
使用draft-04 版本而不使用draft-07 if then 关键字?
【问题讨论】:
-
if/then/else真的只是一个花哨的oneOf。您当然可以使用它。
标签: java json jsonschema