Swagger HashMap属性类型

jpl*_*aza 14 api rest api-doc swagger

有没有办法在模型部分中定义HashMap或Generic Object类型?我有一个返回产品的REST服务,这些产品可以有不同的选项.options属性基本上是一个HashMap,其中id是选项名称,其值是选项值.

Arn*_*ret 12

是的,这是可能的.

在OpenAPI(fka.Swagger)2.0和3.0中,hashmap始终是一个<string, something>map:

  • 密钥始终是字符串,不需要定义.
  • 值类型是您想要的和定义的additionalProperties.

假设您要描述<string, string>类似这样的哈希映射:

{
  "key1": "value1",
  "key2": "value2"
}
Run Code Online (Sandbox Code Playgroud)

相应的OpenAPI 2.0定义将是:

definitions:
  StringStringMap:
    type: object
    additionalProperties:
      type: string
Run Code Online (Sandbox Code Playgroud)

在OpenAPI 3.0中,定义将是:

components:
  schemas:
    StringStringMap:
      type: object
      additionalProperties:
        type: string
Run Code Online (Sandbox Code Playgroud)


<string, object>像这样 的hashmap

{
  "key1": {"someData": "data", "someOtherData": true},
  "key2": {"someData": "data2", "someOtherData": false}
}
Run Code Online (Sandbox Code Playgroud)

将在OpenAPI 2.0中以这种方式定义:

definitions:
  ComplexObject:
    type: object
    properties:
      someData:
        type: string
      someOtherData:
        type: boolean

  StringObjectMap:
    type: object
    additionalProperties:
      $ref: "#/definitions/ComplexObject"
Run Code Online (Sandbox Code Playgroud)

在OpenAPI 3.0中:

components:
  schemas:
    ComplexObject:
      type: object
      properties:
        someData:
          type: string
        someOtherData:
          type: boolean

    StringObjectMap:
      type: object
      additionalProperties:
        $ref: "#/definitions/ComplexObject"
Run Code Online (Sandbox Code Playgroud)

我刚刚在OpenAPI的第4部分(fka Swagger教程)中深入介绍了这一点.

OpenAPI的(FKA.扬鞭)规范简单解释这也.