6

I am using swagger to generate classes in Java and Type script. I have problem defining map property with list of objects as value. I tried to define as follows:

DataMap
type: object
additionalProperties:
 #type: array -- This config does not work.
  $ref: '#/definitions/Data'

Above yml definition generated following code in java:

  class DataMap extends HashMap<String, Data> {
    }

How can I configure yml to generate key with list of data ? something like following class:

 class DataMap extends HashMap<String, List<Data>> {
        }

or

 class DataInfo {
     Map<String, List<Data>> dataMap;
   }

Is this possible with swagger 2.0? I am thinking of defining another DataList class which extends ArrayList then use this class as value to Map.

--------------UPDATE & ANSWER-----------

Thanks @nickb

I am using swagger-codegen-maven-plugin version 2.2.1 and yml definition to generate map as follows:

 DataInfo
    type: object
    properties:
    dataMap:
     type: object
     additionalProperties:
        type: array 
        items:
          $ref: '#/definitions/Data'

1 Answer 1

10

I'm using Swagger codegen v2.1.6 with the following model definitions:

 foo:
    properties:
      baz:
        type: string
  bar:
    properties:
      map:
        type: object
        additionalProperties:
          type: array
          items:
            $ref: '#/definitions/foo'

This generates a Bar Java class with the following field:

Map<String, List<Foo>> map = new HashMap<String, List<Foo>>();

If you're seeing different behavior, you could've stumbled into a regression. Try testing earlier versions, or specifically see if 2.1.6 correctly generates this model.

Sign up to request clarification or add additional context in comments.

4 Comments

Awesome, I will check my swagger library. thanks @nickb
The latest stable version of Swagger Codegen is 2.2.2: github.com/swagger-api/swagger-codegen/releases. Please consider upgrade to the latest stable version to get bug fixes and enhancements.
@nickb Thank you very much, After changing the definition as you suggested it works.
@wing328 I am using 2.2.1 Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.