通过 Swagger/OpenAPI 为附加属性指定多种类型属性、多种、类型、Swagger

2023-09-07 14:22:56 作者:每当生活击倒了我,我不会马上振作起来,我通常就躺在那儿顺便打

我希望在 OpenAPI 中表示以下 JSON 对象:

I am looking to represent the following JSON Object in OpenAPI:

{
  "name": "Bob",
  "age": 4,
  ...
}

属性的数量和属性名称没有完全预先确定,所以我希望使用附加属性.但是,我不太确定它将如何通过 OpenAPI/Swagger 2.0 表示.我试过这个:

The number of properties and the property names are not fully predetermined, so I look to use additionalProperties. However, I'm not too certain how it would be represented through OpenAPI/Swagger 2.0. I tried this:

Person:
  type: object
  additionalProperties:
    type:
      - int
      - string

或等效的 JSON:

{
  "Person": {
    "type": "object",
    "additionalProperties": {
      "type": ["int", "string"]
    }
  }
}

但这并不完全奏效.有什么方法可以保持我想要表示的 JSON 对象的结构,特别是字符串和整数,而不是任意对象类型?

but that didn't quite work. Is there any way to keep the structure of the JSON Object I want to represent, for specifically strings and integers, and not arbitrary object types?

推荐答案

OpenAPI 3.0

OpenAPI 3.0 支持 oneOf 所以你可以使用:

Person:
  type: object
  additionalProperties:
    oneOf:
      - type: string
      - type: integer

OpenAPI 2.0

OpenAPI 2.0 不支持多类型值.您最多可以使用 无类型模式,这意味着附加属性可以是任何东西 - 字符串、数字、布尔值、等等 - 但你不能指定确切的类型.

OpenAPI 2.0

boot返回码规范 spring Spring Boot使用OpenAPI规范

OpenAPI 2.0 does not support multi-type values. The most you can do is use the typeless schema, which means the additional properties can be anything - strings, numbers, booleans, and so on - but you can't specify the exact types.

Person:
  type: object
  additionalProperties: {}

这相当于:

Person:
  type: object
 
精彩推荐