Forum Discussion

willi1s's avatar
willi1s
New Member
5 years ago

[Java] How to get oneOf data from responses

This may be a limitation of my Java knowledge.

 

I am trying to work out how to get the correct oneOf data back from a GET request

Given the simple swagger definition:

openapi: 3.0.1
info:
  title: Inheritance
  description: A description
  contact:
    email: me@example.com
  version: 0.0.0
paths:
  /pets:
    get:
      responses:
        '200':
          description: Updated
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/Cat'
                  - $ref: '#/components/schemas/Dog'
                discriminator:
                  propertyName: petType
components:
  schemas:
    Pet:
      type: object
      required:
        - petType
      properties:
        petType:
          type: string
      discriminator: 
        propertyName: petType
    Dog:     # "Dog" is a value for the pet_type property (the discriminator value)
      allOf: # Combines the main `Pet` schema with `Dog`-specific properties 
        - $ref: '#/components/schemas/Pet'
        - type: object
          # all other properties specific to a `Dog`
          properties:
            bark:
              type: boolean
            breed:
              type: string
              enum: [Dingo, Husky, Retriever, Shepherd]
    Cat:     # "Cat" is a value for the pet_type property (the discriminator value)
      allOf: # Combines the main `Pet` schema with `Cat`-specific properties 
        - $ref: '#/components/schemas/Pet'
        - type: object
          # all other properties specific to a `Cat`
          properties:
            hunts:
              type: boolean
            age:
              type: integer

 

Using the java generator (3.0.19) to generate the client api, I am provided with the petsGet() function, which I can use as follows:

DefaultApi defaultApi = new DefaultApi();
try {
    InlineResponse200 response = defaultApi.petsGet();
} catch (ApiException e)
{
    ...
}

 

My question is, how do I convert the response object to either a Cat or a Dog? 

No RepliesBe the first to reply