首页 文章

Swagger响应类Map

提问于
浏览
3

我有一个返回的REST API,本质上是一个Map(String,Object),其中Object也是

  • 自定义bean(比方说Bean类)或

  • 所有类型Bean的元素列表

在JSON中,这很好地转换为:

{
   "key1":{
      "val1":"some string",
      "val2":"some other string",
      "val3":"another string"
   },
   "key2":[
      {
         "val1":"some string",
         "val2":"some other string",
         "val3":"another string"
      },
      {
         "val1":"some string",
         "val2":"some other string",
         "val3":"another string"
      }
   ]
}

通过swagger注释,有没有办法将这种动态Map指定为响应类?

谢谢

1 回答

  • 0

    我读了'Open API Specification' - 'Add support for Map data types #38' page . 据我所知,它建议使用additionalProperties,但我还没有设法使它与Swagger UI 2.1.4一起使用(参见我的相关问题:Swagger: map of string, Object) .

    我找到了以下解决方法:定义一个对象,一个属性是键,一个内部对象作为“key”属性的值 .

    Swagger UI中的显示是正确的,但是没有人看到它是一张 Map ,因此需要在评论中解释这实际上是一张 Map .

    在你的情况下,我发现曾经有一个Bean,有一个Beans列表有点奇怪:我会发现在第一种情况下拥有一个Bean的数组更合乎逻辑 .

    不过,你可以做,例如:

    your_property: {
        description: "This is a map that can contain several objects indexed by different keys. The value can be either a Bean or a list of Beans.",
        type: object,
        properties: {
            key_for_single_bean: {
                description: "The value associated to 'key_for_single_bean' is a single Bean",
                $ref: "#/definitions/Bean"
            },
            key_for_list_of_beans: {
                description: "The value associated to 'key_for_list_of_beans' is an array of Beans",
                type: array,
                items: {$ref: "#/definitions/Bean"}
            }
        }
    }
    

相关问题