【问题标题】:Json Schema different input formatsJson Schema 不同的输入格式
【发布时间】:2019-11-05 17:29:47
【问题描述】:

我正在 AWS API Gateway 中创建一些模型。我遇到了一个问题,我希望它接收 2 种输入格式:其中一种格式只是字典,另一种是字典数组:

{
    "id":"",
    "name":""
}

[
    {
        "id":"",
        "Family":""
    },
    {
        "id":"",
        "Family":""
    },

    ...

    {
        "id":"",
        "Family":""
    }
]

到目前为止,我已经创建了只接受字典方式的模型:

{  
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Update",
  "type": "object",
  "properties": {
      "id": { "type": "string"},
      "name": { "type": "string"}
  },
  "required": ["id"]
}

请给我一些创建字典数组的技巧。我做了一些研究,但我没有发现任何东西,但我遵循关键字 oneOf 和 anyOf 的方式,但我不确定。

【问题讨论】:

    标签: json amazon-web-services api validation jsonschema


    【解决方案1】:

    anyOf 让您走在正确的轨道上。您应该做什么取决于本身的对象(字典)与数组中的对象之间的相似性。在您的示例中它们看起来不同,所以我会实物回答,然后说明如果它们实际上相同,如何简化事情。


    要使用anyOf,您需要捕获定义字典的关键字

    {
      "type": "object",
      "properties": {
        "id": { "type": "string"},
        "name": { "type": "string"}
      },
      "required": ["id"]
    }
    

    并将其包装在架构根级别的 anyOf

    {  
      "$schema": "http://json-schema.org/draft-04/schema#",
      "title": "Update",
      "anyOf": [
        {
          "type": "object",
          "properties": {
            "id": { "type": "string"},
            "name": { "type": "string"}
          },
          "required": ["id"]
        }
      ]
    }
    

    要为同类型对象的数组编写架构,您需要 items 关键字。

    {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": { "type": "string"},
          "Family": { "type": "string"}
        },
        "required": ["id"]
      }
    }
    

    将它作为第二个元素添加到 anyOf 数组中,你就完美了。


    如果您的唯一对象可以与您的数组元素对象具有相同的架构,那么您可以将该架构编写一次作为定义并在两个地方引用它。

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "title": "Update",
      "definitions": {
        "myObject": {
          "type": "object",
          "properties": {
            "id": { "type": "string"},
            "name": { "type": "string"}
          },
          "required": ["id"]
        }
      },
      "anyOf": [
        { "$ref": "#/definitions/myObject" },
        {
          "type": "array",
          "items": { "$ref": "#/definitions/myObject" }
        }
      ]
    }
    

    【讨论】:

    • 非常感谢您的明确回复!我知道我现在必须做什么;)
    • 我不知道为什么,但是当我作为 Swagger 进行导出时,更新模型会在 swagger 中产生错误,例如:错误:类型:“错误架构”。你知道为什么吗?
    • 我不确定。您收到的错误消息不是很好。验证您提供的内容是否是有效的 JSON 并且对于 swagger 模式有效。
    • 解决了!!事实上,问题来自 Json
    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2018-11-22
    • 2018-07-09
    • 1970-01-01
    相关资源
    最近更新 更多