如何使用 json 模式验证器验证可空类型?

How to validate for nullable types using json schema validator?

我正在使用 play-json-schema-validator 并希望使用 scala 设置集成测试以检查 API 的 JSON 响应模式。

响应的某些字段可以为空,我想对此进行验证。所以一些字段可以是字符串或空值,但它永远不能是数字。

玩转 its playground 我想验证一个对象数组,每个对象的 name 属性 是字符串还是 null。

我想到了这个模式:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Product set",
  "type": "array",
  "items": {
    "title": "Product",
    "type": "object",
    "properties": {
      "name": {
        "type": ["string", null]
      }
    }
  }
}

尽管它验证了字符串和空大小写,但我现在得到了数字的误报。我期待这个 json 的错误,但它验证了:

[
  {
    "name": "Red anger"
  },
  {
    "name": null
  },
  {
    "name": 13
  }
]

如何使用模式验证器将类型的字段声明为可为空?

在架构中引用空值:

"type": ["string", "null"]

您可以在 json schema validation documentation 中阅读相关内容,即:

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.

schema的type属性不接受数组,当时只接受单一类型: "string", "null"... 正如您所指出的,类型应该是字符串,而不是 null => "null"

如果要检查单个字段的多种类型,您需要使用

任何一个,一个,所有

这是一个使用您的输入的示例

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Product set",
  "type": "array",
  "items": {
    "title": "Product",
    "type": "object",
    "properties": {
      "name": {
        "anyOf": [
            {"type":"string"},
            {"type":"null"},
            {"type":"number"}
        ]
      }
    }
  }
}