我正在使用 play-json-schema-validator并希望使用 Scala 设置集成测试以检查 API 的 JSON 响应模式。
响应的某些字段可以为空,我想对此进行验证。所以某些字段可以是字符串或空值,但它永远不能是数字。
在 its playground 上玩我想验证每个对象的对象数组 name
属性是字符串或空值。
我想出了这个模式:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product set",
"type": "array",
"items": {
"title": "Product",
"type": "object",
"properties": {
"name": {
"type": ["string", null]
}
}
}
}
然而,尽管它验证了字符串和 null 大小写,但我现在得到了数字的误报。我期待这个 json 出现错误,但它验证了:
[
{
"name": "Red anger"
},
{
"name": null
},
{
"name": 13
}
]
如何使用模式验证器将类型的字段声明为可为空?
最佳答案
引用架构中的空值:
"type": ["string", "null"]
您可以在 json schema validation documentation 中了解相关信息。 , IE。:
6.1. Validation Keywords for Any Instance Type
6.1.1. type
The value of this keyword MUST be either a string or an array. If it is an array, elements of the array MUST be strings and MUST be unique.
String values MUST be one of the six primitive types ("null", "boolean", "object", "array", "number", or "string"), or "integer" which matches any number with a zero fractional part.
An instance validates if and only if the instance is in any of the sets listed for this keyword.
关于json - 如何使用 json 模式验证器验证可为空类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47592134/