JSON模式-不同对象的数组 [英] JSON Schema - array of different objects

查看:126
本文介绍了JSON模式-不同对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何为不同对象的数组指定JSON模式. 此线程给了我答案的一半,但是当我有每种对象的多个实例时失败.

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"
    }
  ]
}

只有在每种类型都有一个实例时(即,如果" Product "仅出现一次),以下模式将验证上述XML.

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
}

要增加娱乐性,我不能使用" AnyOf "之类的关键字,因为我将此模式嵌入到Swagger 2.0文档中,并且不支持这些关键字.

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.

谢谢

J.

推荐答案

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

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.

这篇关于JSON模式-不同对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆