swagger-api/swagger-codegen-generators

[Spring] @JsonTypeId not set on discriminator property causing serialization issues

Closed this issue · 1 comments

Spring codegen doesn't add set a @JsonTypeId annotation on the field used as the discriminator property, causing duplications of this field when serializing to JSON.

NOTE: This example assumes issue #103 as fixed.

Using these schemas:

Example:
      type: object
      required:
        - baseType
      discriminator:
        propertyName: baseType
      properties:
        baseType:
          type: string
        otherProp:
          type: string
SubExample:
      allOf:
        - $ref: '#/components/schemas/Example'
        - type: object

Will generate this Example class (truncated for illustration):

/**
 * Example
 */
@Validated

@javax.annotation.Generated(value = "io.swagger.codegen.languages.java.SpringCodegen", date = "2018-06-18T16:55:52.608-04:00[America/New_York]")

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

public class Example   {

  @JsonProperty("baseType")
  private String baseType = null;
  
  @JsonProperty("otherProp")
  private String otherProp = null;
}

When trying to serialize an instance of this class as JSON, the discriminator field will be included twice, like so:

{
    "baseType":"SubExample",
    "baseType":"SubExample",
    "otherProp":"some value"
}

A solution

The @JsonTypeId annotation can be used to fix this. By declaring the annotation on the same field used as the discriminator, like so:

public class Example   {

  @JsonProperty("baseType")
  @JsonTypeId
  private String baseType = null;
  
  @JsonProperty("otherProp")
  private String otherProp = null;

An instance of this class would properly serialize to JSON as:

{
    "baseType":"SubExample",
    "otherProp":"some value"
}

@HugoMario @gabe-linux
I also encountered same issue. (Using 2.2.2 version) Why this fix is not present in master?
Or Am I missing something ?