【问题标题】:JSON Schema - array of different objectsJSON Schema - 不同对象的数组
【发布时间】:2018-07-09 16:39:32
【问题描述】:

我想知道如何为一组不同的对象指定 JSON 模式。 This thread 给了我一半的答案,但是当我对每种类型的对象都有多个实例时会失败。

这是一个示例 XML,基于 example given here 但重复了“Product”对象:-

{
  "things": [
    {
      "entityType" : "Product",
      "name" : "Pepsi Cola",
      "brand" : "pepsi"
    },
    {
      "entityType" : "Product",
      "name" : "Coca Cola",
      "brand" : "coke"
    },
    {
      "entityType" : "Brand",
      "name" : "Pepsi Cola"
    }
  ]
}

只有当每种类型都有一个实例时(即“Product”只出现一次),以下架构才会验证上述 XML。

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "https://schemas.example.com/things",
  "title": "Things",
  "description": "Some things",
  "type": "object",
  "required": [
    "things"
  ],
  "properties": {
    "things": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "required": [
            "entityType",
            "name"
          ],
          "properties": {
            "entityType": {
              "type": "string",
              "enum": [
                "Product"
              ]
            },
            "name": {
              "type": "string"
            },
            "brand": {
              "type": "string"
            }
          }
        },
        {
          "type": "object",
          "required": [
            "entityType",
            "name"
          ],
          "properties": {
            "entityType": {
              "type": "string",
              "enum": [
                "Brand"
              ]
            },
            "name": {
              "type": "string"
            }
          }
        }
      ]
    }
  },
  "additionalProperties": false
}

为了增加娱乐性,我不能使用像“AnyOf”这样的关键字,因为我将此架构嵌入到 Swagger 2.0 文档中,并且不支持这些关键字。

谢谢,

J.

【问题讨论】:

  • 对象可以有其他不同的属性名称吗?在您的示例中,它们都具有几乎相同的结构,只是 brand 属性是可选的。
  • 不,它们完全不同;只有几个属性具有相同的名称。
  • 嗯...为什么对这个问题投反对票?

标签: json swagger jsonschema swagger-2.0


【解决方案1】:

没有anyOf,你就不走运了。您可以做的最好的事情是使用一个涵盖所有选项的架构。这不是一个很好的解决方案,但总比没有好。

【讨论】:

  • 天哪。我以前很怕那个。 Swagger 缺乏对这些构造的支持已在 Open API 3.0 中得到修复……但我们与 2.0 相关联。感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 2013-03-02
相关资源
最近更新 更多