如何强制JSON数组仅接受$ref定义的value类型?
解决Newtonsoft.Json v11.0.2中JSON Schema数组仅接受指定对象类型的问题
咱们先搞清楚为什么你现在的Schema没法拒绝像"string"这类非对象的数组项,再给出正确的修复方案。
问题根源
你的/definitions/value定义里没有明确指定"type": "object"。在JSON Schema Draft-07规范中,如果一个Schema不声明type关键字,它默认会匹配所有数据类型。
而required、properties这类关键字只有当实例是对象时才会生效——如果实例是字符串、数字这类非对象类型,这些关键字不会触发验证失败。这就是为什么你测试用的JSON里的字符串项能通过验证:Schema从一开始就没检查过数组项必须是对象。
修正后的JSON Schema
只需要在value定义里加上"type": "object",就能强制每个数组项都必须是符合要求的对象:
{ "$schema": "http://json-schema.org/draft-07/schema", "$id": "http://some.thing/json", "type": "object", "definitions": { "value": { "$id": "/definitions/value", "type": "object", // 关键:明确指定类型为对象 "required": ["a", "b", "c"], "properties": { "a": { "$id": "/properties/value/a", "type": "string" }, "b": { "$id": "/properties/value/b", "type": "string" }, "c": { "$id": "/properties/value/c", "type": "string" } } } }, "required": ["values"], "properties": { "values": { "$id": "/properties/values", "type": "array", "items": { "$id": "/properties/values/item", "$ref": "/definitions/value" }, "uniqueItems": true } } }
修复后的验证效果
- 依然会正确拒绝缺少必填字段的对象(比如
{ "values": [ { "a": "a2", "b": "b2" } ] }),因为required关键字现在会在合法的对象实例上生效。 - 会拒绝包含非对象项的数组(比如你测试用的
{ "values": [ { "a": "a2", "b": "b2", "c": "c3" }, "string" ] }),因为value定义明确要求实例必须是对象,字符串不符合这个类型要求。
为什么你之前的尝试没用?
additionalItems: false:这个关键字只有在items是Schema数组(而非单个Schema)时,才会限制超出定义的额外项,和你要限制项的类型完全无关,所以不适用。- 在
items内添加additionalProperties: false:这个关键字是限制对象实例不能有未定义的额外属性,和项本身的类型无关,所以没法阻止非对象类型的项通过验证。
内容的提问来源于stack exchange,提问作者be_cracked
相关产品推荐
相关产品推荐

