nickshoe
nickshoe

Reputation: 103

Why OpenAPI discriminator property gets serialized twice by Jackson in Java generated code?

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 uses 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 configure the Jackson ObjectMapper object to ignore this kind of situations.

ObjectMapper om = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Upvotes: 7

Views: 9226

Answers (5)

Soham Dixit
Soham Dixit

Reputation: 125

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

It's being generated as -

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

which adds an extra property to 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.

Upvotes: 4

Paul Barnes
Paul Barnes

Reputation: 27

As Florimon says in an earlier answer, you can eliminate the double discriminator field serialization problem by not including the discriminator in the OpenApi properties list, which then causes UnrecognizedPropertyException on deserialization. And that can be fixed by removing "visible=true" property (or setting to false) in the @JsonTypeInfo annotation. Which is painful for generated code.

A workaround is to use Jackson-mix in annotations to replace the generated @JsonTypeInfo annotations. Create a mixin class with the desired visible=false like this:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, visible = false, property = "discriminator")
abstract class MyMixIn {}

Add register with your ObjectMapper like this:

objectMapper.addMixIn(MyGenerated.class, MyMixIn.class)

You should also be able to customize the ObjectMapper used in client/server to have it use the mix in. For example, in a jax-rs server application, you can implement and register a @Provider class which implements ContextResolver<ObjectMapper>.

On the client side, register it with something like this:

ClientBuilder.newClient().register(JacksonFeature.class).register(MyObjectMapperProvider.class)

Upvotes: 1

Ena
Ena

Reputation: 3621

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

Upvotes: 4

slavek
slavek

Reputation: 401

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

Upvotes: 1

Florimon van Putte
Florimon van Putte

Reputation: 21

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

Upvotes: 2

Related Questions