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

标签 json scala playframework null json-schema-validator

我正在使用 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/

相关文章:

playframework - 如何从 play framework 2.5.x 构建 jar

playframework - Play 2.4 - 在 Eager 单例模块中使用 Ebean

c# - JSON.NET 阅读器问题

java - JSONparser 读取句子中的第一个单词

Javascript 无法处理 JSON 文本文件

java - 如何将 ISO 8601 持续时间转换为秒

scala - 是否有任何带有 Actor 模型的 Scala 网络库

java - 如何在 Java 中使用/反序列化 .Net WCF 服务 JSON 响应

scala - 从sbt调用我的测试时不包括ScalaTest测试

playframework - 如何禁用 Play !在测试模式下运行应用程序时妨碍模块测试?