简体   繁体   English

当不同对象中的类型不同时,具有相同类型项数组的JSON对象的模式

[英]Schema for JSON object with an array of items of the same type when this type is different in different objects

I want to describe schema of an object which has a property of array type. 我想描述具有数组类型属性的对象的架构。 Items in that array must be of the same type. 该数组中的项目必须具有相同的类型。 But two different objects can have different type for items in that array: 但是对于该数组中的项目,两个不同的对象可以具有不同的类型:

// object_1
{
  <...>,
  "array_of_some_type": [1, 2, 3, 4, 5],
  <...>
}

// object_2
{
  <...>,
  "array_of_some_type": ["one", "two", "three"],
  <...>
}

I have tried using of oneOf keyword: 我尝试使用oneOf关键字:

{
  "type": "object",
  "properties": {
    <...>
    "array_of_some_type": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true,
      "items": {
        "oneOf": [
          { "type": "number" },
          { "type": "string" },
          { "type": "object" }
        ]
      },
      "additionalItems": false
    },
    <...>
  },
  "required": [ "array_of_some_type" ],
  "additionalProperties": false
}

But it is wrong because this schema is valid for invalid in my case object: 但这是错误的,因为此架构在我的case对象中对无效有效:

// invalid_object
{
  <...>,
  "array_of_some_type": [1, "two", 3],
  <...>
}

The correct schema can look like: 正确的架构如下所示:

{
  "type": "object",
  "properties": {
    <...>
    "array_of_some_type": {
      "oneOf": [
        {
          "type": "array",
          "minItems": 1,
          "uniqueItems": true,
          "items": { "type": "number" },
          "additionalItems": false
        },
        {
          "type": "array",
          "minItems": 1,
          "uniqueItems": true,
          "items": { "type": "string" },
          "additionalItems": false
        },
        {
          "type": "array",
          "minItems": 1,
          "uniqueItems": true,
          "items": { "type": "object" },
          "additionalItems": false
        }
      ]
    },
    <...>
  },
  "required": [ "array_of_some_type" ],
  "additionalProperties": false
}

BUT there are a lot of duplicates of identical array's properties. 但是,有很多相同数组属性的重复项。 Is there any way to tune the second schema to avoid repetitions? 有什么方法可以调整第二个架构以避免重复吗? Or any other suggestions? 或其他建议?

You can put only the part that varies in the oneOf clause. 您只能将不同的部分放在oneOf子句中。 I think JSON-Schema would have to support something like Java's generics in order to express this any cleaner. 我认为JSON-Schema必须支持Java泛型之类的东西,才能表达出更简洁的表达。

{
  "type": "object",
  "properties": {
    "array_of_some_type": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true,
      "oneOf": [
        { "items": { "type": "number" } },
        { "items": { "type": "string" } },
        { "items": { "type": "object" } }
      ]
    }
  },
  "required": [ "array_of_some_type" ],
  "additionalProperties": false
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM