【问题标题】:How to describe a map with object keys in OpenAPI/Swagger?如何在 OpenAPI/Swagger 中使用对象键描述地图?
【发布时间】:2018-06-29 07:21:19
【问题描述】:

在我的 REST API 中,我想使用哈希图 Map<Foo, List<Bar>>,其中 FooBar 是用户定义的类。如何在 OpenAPI (Swagger) 中描述这样的地图?

【问题讨论】:

标签: rest swagger openapi


【解决方案1】:

OpenAPI (Swagger) 仅支持带有字符串键的映射,例如:

{
  "en":  "Hello",
  "fr":  "Bonjour"

   ^^ key is a string
}

无法使用非字符串键定义映射,例如Map<Foo, Bar>。您可以在 OpenAPI 规范存储库中提交功能请求:https://github.com/OAI/OpenAPI-Specification/issues

您最多可以将哈希图定义为 type: object,这意味着任意对象。

【讨论】:

  • OpenAPI 模式定义基于 JSON 模式,而 JSON 哈希图使用字符串键。你认为Map<Foo, Bar> 将如何用 JSON 表示?
【解决方案2】:

你可以通过additionalProperties做到这一点
docs

components:
  schemas:
    Messages:        # <---- map
      type: object
      additionalProperties:
        type: string

在json中表示为:

{
  "Alex":  "Hello",
  "Ann":  "Hi!"

   ^^ key is a string
}

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 2018-12-05
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2020-03-30
    相关资源
    最近更新 更多