如何在JSON Schema中限制Employee对象不可全属性为null?
解决方案
要实现“4个属性允许部分为null,但不允许全部为null”的校验,你可以通过两种方式实现:
方法一:使用not排除全为null的情况
这种方式更简洁,直接校验对象不是所有指定属性都为null的情况:
"employee": { "type": "object", "default": {}, "properties": { "empName": { "type": ["object", null] }, "empAge": { "type": ["object", null] }, "empAddress": { "type": ["object", null] }, "empContact": { "type": ["object", null] } }, "not": { "properties": { "empName": { "const": null }, "empAge": { "const": null }, "empAddress": { "const": null }, "empContact": { "const": null } }, "required": ["empName", "empAge", "empAddress", "empContact"] } }
逻辑说明:
not块定义了需要排除的非法情况:四个属性都存在且值为nullrequired确保四个属性都被校验(如果请求中缺失某个属性,默认不会触发该属性的校验,所以需要强制要求这些属性存在,再判断它们是否全为null)
方法二:使用anyOf指定至少一个属性不为null
如果你更倾向于明确列出合法情况,可以用anyOf逐个指定“至少有一个属性不为null”:
"employee": { "type": "object", "default": {}, "properties": { "empName": { "type": ["object", null] }, "empAge": { "type": ["object", null] }, "empAddress": { "type": ["object", null] }, "empContact": { "type": ["object", null] } }, "anyOf": [ { "properties": { "empName": { "type": "object" } }, "required": ["empName"] }, { "properties": { "empAge": { "type": "object" } }, "required": ["empAge"] }, { "properties": { "empAddress": { "type": "object" } }, "required": ["empAddress"] }, { "properties": { "empContact": { "type": "object" } }, "required": ["empContact"] } ] }
逻辑说明:
anyOf中的每一项表示“某一个属性存在且不为null”- 只要满足其中任意一项,整个对象就通过校验
注意事项
- 如果你允许请求中缺失部分属性(而不是必须存在但为null),可以去掉
required字段,调整校验规则为:判断属性要么不存在要么不为null,但至少有一个属性存在且不为null。 - 确保你的JSON Schema校验器支持Draft-07及以上版本(
const关键字在Draft-07中引入)。
内容的提问来源于stack exchange,提问作者Ravi
相关产品推荐
相关产品推荐

