3

I have a REST API that returns, essentially a Map of (String, Object) where Object is either

  1. A custom bean (let's say class Bean) or
  2. A List of elements, all of type Bean

In JSON, this translates very well to:

{
   "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"
      }
   ]
}

Via swagger annotations, is there a way to specify this kind of a dynamic Map as the response class?

Thanks

zeiger
  • 700
  • 5
  • 16

1 Answers1

0

I read the 'Open API Specification' - 'Add support for Map data types #38' page. As far as I understand, it recommends to use additionalProperties, but I haven't managed to make it work with Swagger UI 2.1.4 (see my related question: Swagger: map of string, Object).

I have found the following work-around: define an object, with one property that is the key, and with an inner object as the value for the "key" property.

The display in Swagger UI is correct, but one does not see it is a map, so it is then needed to explain in the comment that this is actually a map.

In your case, I find it a bit weird to have once a Bean, and once a list of Beans: I would find it more logical to have an array of one Bean in the first case.

Still, you could do, for example:

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"}
        }
    }
}
Community
  • 1
  • 1
Xavier Lamorlette
  • 1,152
  • 1
  • 12
  • 20