JSON Schema - array of different objects

蓝咒 提交于 2021-02-19 07:44:20

问题


I'd like to know how to specify a JSON schema for an array of different objects. This thread gives me half the answer, but fails when I have multiple instances of each type of object.

Here's a sample XML, based on the example given here but with the "Product" object being repeated:-

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

The following schema will validate the above XML only when there is a single instance of each type (i.e. if "Product" only appears once).

{
  "$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
}

To add to the entertainment, I can't use keywords like "AnyOf", as I'm embedding this schema into a Swagger 2.0 document, and those keywords aren't supported.

Thanks,

J.


回答1:


Without anyOf you're out of luck. The best you can do is use one schema that covers all of the options. It not a great solution, but it's better than nothing.



来源:https://stackoverflow.com/questions/48527444/json-schema-array-of-different-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!