【问题标题】:Allow only $ref type in JSON array在 JSON 数组中只允许 $ref 类型
【发布时间】:2018-05-21 12:23:27
【问题描述】:

我有以下模式,其中数组values 只接受value 类型的对象。我正在使用Newtonsoft.Json v11.0.2 进行验证。

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "http://some.thing/json",
  "type": "object",
  "definitions": {
    "value": {
      "$id": "/definitions/value",
      "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"
    }
  ]
}

但确实验证

{
  "values": [
    {
      "a": "a2",
      "b": "b2",
      "c": "c3"
    },
    "string"
  ]
}

这是不应该的。

如何强制只有values 可以在数组中? "additionalItems": false 限制了项目的数量,而“项目”中的 "additionalProperties": false 似乎什么都不做,所以这些也不是我想要的。

【问题讨论】:

    标签: json json.net jsonschema


    【解决方案1】:

    您正在尝试验证 values 数组的有效项目,而您的项目定义中的 "additionalProperties": false 只会影响一个对象。

    相反,您需要将"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": {
            "$ref": "/definitions/value"
          }
        },
        "uniqueItems": true
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 2018-10-09
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      相关资源
      最近更新 更多