如何在map中定义键的枚举,Swagger

epggiuax  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(107)

我需要定义一个Map。但我也想限制可能的键。
这就是我试图做的。

type: object
    description: Key Value Map with user data. Possible values for the keys ("KEY_1", "KEY_2", "KEY_3")
    additionalProperties:
      type: object

是否可以使用枚举来定义键?(map返回int String,Object。但这不是问题的一部分)
感谢你的帮助.

z4bn682m

z4bn682m1#

当你使用additionalPropertie时,你不能定义接受的键集。但是如果我的理解是正确的,那么这个JSON的hashmap的两个例子可能是:
JSON示例1:

{
  "KEY_1": { ... },
  "KEY_2": { ... },
  "KEY_3": { ... }
}

JSON示例2:

{
  "KEY_1": { ... },
  "KEY_3": { ... }
}

这个带有一组定义好的键的散列表基本上是一个对象,它包含可选的(即非必需的)对象类型的属性,因此可以像任何其他对象一样定义:

type: object
properties:
  KEY_1:
    type: object
  KEY_2:
    type: object
  KEY_3:
    type: object

nb:使用$ref来避免为每个KEY属性定义对象是一个好主意:

type: object
properties:
  KEY_1:
    $ref: '#/definitions/TheObjectDefinition'
  KEY_2:
    $ref: '#/definitions/TheObjectDefinition'
  KEY_3:
    $ref: '#/definitions/TheObjectDefinition'
mo49yndu

mo49yndu2#

您可以使用列表模拟字典/Map。
首先定义一个条目对象,在其中可以限制类型。
然后将Map定义为一个条目数组。

Entry:
  type: object
  properties:
    key:
      $ref: '#/components/schemas/SomeEnum'
    value:
      type: string
SimulatedMap:
  type: object
  properties:
    entries:
      type: array
      items:
        $ref: '#/components/schemas/Entry'

相关问题