3

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

  1. 一个自定义 bean(比方说类 Bean)或
  2. 元素列表,所有类型为 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 指定为响应类?

谢谢

4

1 回答 1

0

我阅读了“开放 API 规范”-“添加对地图数据类型 #38 的支持”页面。据我了解,它建议使用 additionalProperties,但我还没有设法使其与 Swagger UI 2.1.4 一起使用(请参阅我的相关问题:Swagger: map of string, Object)。

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

Swagger UI中的显示是正确的,但是看不出是地图,所以需要在评论中说明这其实是地图。

在您的情况下,我发现一次拥有一个 Bean 和一次 Bean 列表有点奇怪:我会发现在第一种情况下拥有一个 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"}
        }
    }
}
于 2016-03-22T16:31:53.217 回答