Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why discriminator property gets serialized twice?

I'm using OpenAPI 3.0 inheritance in components schemas and I have the (Java) classes generated by openapi-generator (which uses Jackson).

Why the discriminator property gets serialized twice in the resulting JSON?

This is a JHipster API-First project, which should use openapi-generator for generating the Java model (POJOs with Jackson annotations) and API controllers (interfaces with Spring's @Api annotations).

By following the OpenAPI 3.x documentation/examples, it seems that the property used as discriminator must also be specified in the properties list of the schema.

This way, the generated Java class seems to differ from the Jackson guidelines for polymorphic type handling with annotations (here), where the property used as discriminator must not be present in the class. Instead, the generated code also includes this property as a class attribute with getter/setter. This causes the JSON output to include the property twice, as shown below.

I've also tried to remove the property from the OpenAPI properties list, leaving intact the discriminator part; this way the generated code corresponds to the Jackson's guidelines and the serialization works just fine. On the other hand, I get an error during the deserialization process because the (removed) property is not found in the target class.

Following the OpenAPI 3.x doc guidelines:

TicketEvent:
  type: object
  description: A generic event
  discriminator:
    propertyName: type
  required:
    - id
    - sequenceNumber
    - timestamp
    - type
  properties:
    id:
      type: integer
      format: int64
      readOnly: true
    sequenceNumber:
      type: integer
      readOnly: true
    timestamp:
      type: string
      format: date-time
      readOnly: true
    type:
      type: string
      readOnly: true
TicketMovedEvent:
  description: A ticket move event
  allOf:
    - $ref: '#/components/schemas/Event'
    - type: object
      required:
        - source
        - target
      properties:
        source:
          $ref: '#/components/schemas/Queue'
        target:
          $ref: '#/components/schemas/Queue'

Generated class:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = TicketMovedEvent.class, name = "TicketMovedEvent")
})

public class TicketEvent   {
   ...

   @JsonProperty("type")
   private String type;

The JSON includes the property twice:

{
        ...
    "type": "TicketMovedEvent",
    "type": null,
        ...
}

Removing the discriminator property from properties list:

TicketEvent:
  type: object
  description: A generic event
  discriminator:
    propertyName: type
  required:
    - id
    - sequenceNumber
    - timestamp
  properties:
    id:
      type: integer
      format: int64
      readOnly: true
    sequenceNumber:
      type: integer
      readOnly: true
    timestamp:
      type: string
      format: date-time
      readOnly: true

Generated class without type property:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = TicketMovedEvent.class, name = "TicketMovedEvent")
})

public class TicketEvent   {
   ...

   // now the "type" property is missing
})

The JSON now is correct:

{
        ...
    "type": "TicketMovedEvent",
        ...
}

I would expect that, by following the OpenAPI 3.x guidelines, the generated class to be properly serialized/deserialized.

(sidenote)

During deserialization, by using the aforementioned approach, you might get the following error:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "type" (class it.blutec.bludesk.web.api.model.TicketMovedEvent), not marked as ignorable ...

To fix this, you need to configured the Jackson ObjectMapper object to ignore this kind of situations.

ObjectMapper om = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
like image 435
nickshoe Avatar asked Aug 29 '19 08:08

nickshoe


4 Answers

I Just Ran into the same issue. The problem is with the @JsonTypeInfo annotation on the generated model class.

Its being generated as -

@JsonTypeInfo(... include = JsonTypeInfo.As.PROPERTY ...)

which adds an extra property in the model.

If I change it in the generated code to -

@JsonTypeInfo(... include = JsonTypeInfo.As.EXISTING_PROPERTY ...)

It uses the property which is already in the model and everything works fine.

However, of-course this change is lost when I regenerate the code. It'd be great if someone has found a permanent solution to this.

like image 148
Soham Avatar answered Nov 18 '22 20:11

Soham


Just ran into this myself. Not including the discriminator field in the OpenApi properties list does indeed take care of the double-field problem upon serialization, while causing an UnrecognizedPropertyException upon deserialization. With some trial and error, I found that the 2nd problem can be solved by deleting the "visible = true" property (or setting it to false) of the @JsonTypeInfo annotation in the generated code. (If you have your build process setup to always re-generate code from the open API spec then, of course, this is not a real solution).

like image 37
Florimon van Putte Avatar answered Nov 18 '22 19:11

Florimon van Putte


Just want to add a workaround for the issue described in Soham's answer.

If you are using spring-boot-maven-plugin you can override the mustache template in the project to fix the generated code.

Add a folder in the project's root named openapi-generator-templates.

In the pom.xml file add this line in the plugin's configuration node (NOT configOptions)

<templateDirectory>${project.basedir}/openapi-generator-templates</templateDirectory>

Inside the folder copy the mustache template from openapi-generator project on Github.

I am using kotlin-spring generator so for me the template was here.

Edit the mustache file replacing JsonTypeInfo.As.PROPERTY with JsonTypeInfo.As.EXISTING_PROPERTY

(As a side note, in kotlin-spring generator to have inheritance working you should also use a similar workaround for the dataClass.mustache template. More info about this bug here).

like image 2
Ena Avatar answered Nov 18 '22 21:11

Ena


I believe I solved this in https://github.com/OpenAPITools/openapi-generator/pull/5120 which is supposed to be released with openapi-generator 4.3 release. Feel free to check it out (the oneOf support should also be vastly improved thanks to that PR).

like image 1
slavek Avatar answered Nov 18 '22 21:11

slavek