JSON模式:必填字段上的XOR
JSON模式有,它列出了JSON对象中所需的字段。例如,以下(简化)模式验证向用户发送文本消息的调用:JSON模式:必填字段上的XOR,json,jsonschema,json-schema-validator,required-field,Json,Jsonschema,Json Schema Validator,Required Field,JSON模式有,它列出了JSON对象中所需的字段。例如,以下(简化)模式验证向用户发送文本消息的调用: { "type": "object", "properties": { "userId": { "type": "string" }, "text": { "type": "string" }, }, "required": ["userId", "text"] } 假设我希望启用向多个用户发送消息,即具有userId字段或userId数组(但
{
"type": "object",
"properties": {
"userId": { "type": "string" },
"text": { "type": "string" },
},
"required": ["userId", "text"]
}
假设我希望启用向多个用户发送消息,即具有userId
字段或userId
数组(但不是两者都有或两者都没有)。有没有办法在JSON模式中表达这样的条件
当然,在这种情况下,有一些方法可以解决这个问题-例如,一个带有单个元素的
用户ID
数组-但一般情况下是有趣和有用的。一点也不优雅,但我认为您可以从allOf
和oneOf
中破解出来。比如:
{
"allOf" : [
{
"type" : "object",
"properties" : {
// base properties come here
}
},
"oneOf" : [
{
"properties" : {
"userIds" : {"type" : "array"}
},
"required" : ["userIds"]
},
{
"properties" : {
"userId" : {"type" : "number"}
},
"required" : ["userId"]
}
]
]
}
您现在可能已经解决了这个问题,但这将通过在字段的
类型上使用oneOf
实现
{
“类型”:“对象”,
“财产”:{
“用户ID”:{
“其中之一”:[
{
“类型”:“字符串”
},
{
“类型”:“数组”,
“项目”:{
“类型”:“字符串”
}
}
]
},
“文本”:{
“类型”:“字符串”
}
},
“必需”:[“用户ID”,“文本”]
}