Skip to content

[JAVA] Discriminator not used in JSON.java #10196

Closed
swagger-api/swagger-codegen-generators
#1106

Description

@gravelld
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

Activity

  1. changed the title [-][JAVA] Discriminator not used in JSON[/-] [+][JAVA] Discriminator not used in JSON.java[/+] on Apr 21, 2020
  2. Yingsheng-eroad commented on Jul 16, 2020

    @Yingsheng-eroad

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

  3. mdashti commented on Jul 27, 2020

    @mdashti

    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.

  4. dordal commented on Oct 13, 2020

    @dordal

    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.

  5. mgazim commented on Jan 29, 2021

    @mgazim

    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 :)

  6. rhvonlehe commented on Feb 2, 2021

    @rhvonlehe

    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.

  7. dawnstrider commented on Apr 10, 2021

    @dawnstrider
  8. alexnb commented on Aug 6, 2021

    @alexnb

    This seems to be fixed with 3.0.27

  9. dawnstrider commented on Oct 17, 2022

    @dawnstrider

    Still reproducible with the swagger json from Atlassian and codegen 3.0.35

  10. jonmartinsolaas commented on Jan 27, 2023

    @jonmartinsolaas

    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

  11. self-assigned this
    on Feb 6, 2023
  12. HugoMario commented on Feb 19, 2023

    @HugoMario
    Contributor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions