Masta
Masta

Reputation: 149

Swagger codegen deserialize dynamic reponse

From my Java backend I'm consuming another backend which I don't manage and it's API definition is not available. I'm creating the OpenAPI definition of it's services and using Swagger Codegen to generate the client.

There is an endpoint which returns a complex object:

{
    "total": 151,
    "version": 4,
    "dynamicItem1": [
        "codeDynamicItem1",
        293,
        63700,
        19,
        "nameDynamicItem1",
        "",
        "",
        "",
        0,
        -64
    ],
    "dynamicItem2": [
        "codeDynamicItem2",
        237,
        40000,
        478,
        "nameDynamicItem2",
        "string1",
        "string2",
        "string3",
        0,
        0
    ]

}

In that object the total and version are always there but on the same level there are hundreds of those dynamic items. The key is predictable in the example above but in reality is a sequence of letter and numbers, something like "245df921". The dynamic items are always arrays with the same number of items and in the same expected positions.

To parse that object I'm using additionalProperties beacuse I read that it's the right way to parse hashmaps, but seems like I'm not applying it correctly.

Currently my OpenAPI representation looks like this:

openapi: 3.0.2
info:
  version: 1.0.0
  title: title
  description: description
paths:
  /complexObject:
    get:
      responses:
        '200':
          description: "OK"
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Object'
components:
  schemas:
    Object:
      type: object
      properties:
        total:
          type: number
          example: 151
        version:
          type: number
          example: 4
        additionalProperties:
          type: array
          items:
            type: string
            nullable: true

Using that implementation the total and version are returned properly but in the response object there is an additionalProperties attribute with null value.

What am I missing?

Upvotes: 1

Views: 534

Answers (1)

Helen
Helen

Reputation: 97982

additionalProperties needs to be on the same level as properties.

Also, since those dynamic array are multi-type (string / integer) you need oneOf to define possible item types.

components:
  schemas:
    Object:
      type: object
      properties:
        total:
          type: number
          example: 151
        version:
          type: number
          example: 4
      additionalProperties:   # <-----
        type: array
        items:
          oneOf:              # <-----
            - type: string
              nullable: true
            - type: integer

Upvotes: 0

Related Questions