swagger-codegen icon indicating copy to clipboard operation
swagger-codegen copied to clipboard

[JAVA] Discriminator not used in JSON.java

Open gravelld opened this issue 6 years ago • 10 comments

Description

When I generate client libs for an OpenAPI 3.0.1 YAML, discriminator settings are ignored in the generated JSON deserialisation code.

This means when deserialising JSON we can't enforce polymorphism/composition.

Swagger-codegen version

3.0.19

Swagger declaration file content or url
openapi: 3.0.1
info:
  title: Inheritance
  description: A description
  contact:
    email: [email protected]
  version: 0.0.0
paths:
  /pets:
    patch:
      requestBody:
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/Cat'
                - $ref: '#/components/schemas/Dog'
              discriminator:
                propertyName: petType
      responses:
        '200':
          description: Updated
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

The command line:

$ java -jar swagger-codegen-cli.jar generate \
-i inheritance.yaml \
-l java \
-o java

Generates this in JSON:

GsonFireBuilder fireBuilder = new GsonFireBuilder()
  .registerTypeSelector(Pet.class, new TypeSelector<Pet>() {
    @Override
    public Class<? extends Pet> getClassForElement(JsonElement readElement) {
        Map<String, Class<? extends Pet>> classByDiscriminatorValue = new HashMap<>();
            classByDiscriminatorValue.put("Cat".toUpperCase(), Cat.class);
            classByDiscriminatorValue.put("Dog".toUpperCase(), Dog.class);
            classByDiscriminatorValue.put("Pet".toUpperCase(), Pet.class);
        return getClassByDiscriminator(
                    classByDiscriminatorValue,
                    getDiscriminatorValue(readElement, ""));
    }
  })

Note the empty "" where the discriminator value (petType) should be.

When I try to deserialize:

java.lang.IllegalArgumentException: missing discriminator field: <>
	at io.swagger.client.JSON.getDiscriminatorValue(JSON.java:124)
	at io.swagger.client.JSON.access$0(JSON.java:121)
	at io.swagger.client.JSON$1.getClassForElement(JSON.java:62)
	at io.gsonfire.gson.TypeSelectorTypeAdapterFactory$TypeSelectorTypeAdapter.read(TypeSelectorTypeAdapterFactory.java:65)
	at io.gsonfire.gson.NullableTypeAdapter.read(NullableTypeAdapter.java:36)
	at io.gsonfire.gson.HooksTypeAdapter.deserialize(HooksTypeAdapter.java:86)
	at io.gsonfire.gson.HooksTypeAdapter.read(HooksTypeAdapter.java:54)
	at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
	at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
	at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
	at com.google.gson.Gson.fromJson(Gson.java:932)
	at com.google.gson.Gson.fromJson(Gson.java:870)

When I generate using OpenAPI Generator::4.3.0:

GsonFireBuilder fireBuilder = new GsonFireBuilder()
        .registerTypeSelector(Pet.class, new TypeSelector() {
            @Override
            public Class getClassForElement(JsonElement readElement) {
                Map classByDiscriminatorValue = new HashMap();
                classByDiscriminatorValue.put("Dog".toUpperCase(Locale.ROOT), Dog.class);
                classByDiscriminatorValue.put("Cat".toUpperCase(Locale.ROOT), Cat.class);
                classByDiscriminatorValue.put("Pet".toUpperCase(Locale.ROOT), Pet.class);
                return getClassByDiscriminator(classByDiscriminatorValue,
                        getDiscriminatorValue(readElement, "petType"));
            }
  })
;

(petType is populated here).

Command line used for generation

Using the Gradle plugin, config as above.

Steps to reproduce

gradle generateSwaggerCodeInheritance

gravelld avatar Apr 21 '20 13:04 gravelld

Using OpenAPI tools, I have an issue, if I choose an enum as the discriminator. incompatible types: String cannot be converted to DeviceType

Yingsheng-eroad avatar Jul 16 '20 21:07 Yingsheng-eroad

i encountered the exact same issue and took me a while to figure out it's not a misspelling on my side! Would really apprecite if you could fix this issue.

mdashti avatar Jul 27 '20 08:07 mdashti

This is more than just Java; I've seen it in PHP and Python ( see #10168 ), and I believe it may be an issue in all languages.

dordal avatar Oct 13 '20 04:10 dordal

Are there any plans to fix this? Experiencing the same issue on swagger-codegen 3.0.24 with Java. I'm not an expert in this so any workarounds are appreciated :)

mgazim avatar Jan 29 '21 20:01 mgazim

I'm seeing the same thing with Swagger-codegen 2.4.18. This is the 2nd bug I've encountered, the first being code that was generated was invalid - invalid methods were being called against an imported library.

Actually what I am seeing is a bit different. I have polymorphism using 'allOf' instead of 'oneOf', so I only ever have 1 leaf class from any base class. In my case I was able to just delete the code it was generating to deal with discriminators since it made no sense. The types were already being determined just fine.

rhvonlehe avatar Feb 02 '21 05:02 rhvonlehe

Bug reproducable with following API spec: https://developer.atlassian.com/cloud/jira/platform/swagger.v3.json and swagger codegen: 3.0.25

dawnstrider avatar Apr 10 '21 21:04 dawnstrider

This seems to be fixed with 3.0.27

alexnb avatar Aug 06 '21 09:08 alexnb

Still reproducible with the swagger json from Atlassian and codegen 3.0.35

dawnstrider avatar Oct 17 '22 13:10 dawnstrider

Seems to work with openapi-generator. At least for my little hello-world-test.

java -jar openapi-generator-cli.jar generate -i https://developer.atlassian.com/cloud/jira/platform/swagger-v3.v3.json -g java -o ./jira-client

jonmartinsolaas avatar Jan 27 '23 10:01 jonmartinsolaas

This has been fixed by https://github.com/swagger-api/swagger-codegen-generators/pull/1110/commits/2bd73fbbcb29240c5e41019a39345aa418528400 and https://github.com/swagger-api/swagger-codegen/pull/12070

HugoMario avatar Feb 19 '23 21:02 HugoMario