Skip to content

Duplicate JSON property when @JsonTypeInfo.property is also regular bean property #392

@vojtechhabarta

Description

@vojtechhabarta

Consider following example which uses Jackson library:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind", include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
    @JsonSubTypes.Type(value = DuplicateKind1.class, name = "kind_1"),
    @JsonSubTypes.Type(value = DuplicateKind2.class, name = "kind_2"),
})
abstract class DuplicateKind {
    public String kind;
}
class DuplicateKind1 extends DuplicateKind {
}
class DuplicateKind2 extends DuplicateKind {
}

If instance is created and serialized using Jackson:

DuplicateKind1 object = new DuplicateKind1();
object.kind = "kind_invalid";
System.out.println(new ObjectMapper().writeValueAsString(object));

Jackson generates following invalid JSON:

{
    "kind": "kind_1",
    "kind": "kind_invalid"
}

where first kind property comes from @JsonTypeInfo annotation and second comes from DuplicateKind.kind field. (Tested with Jackson 2.9.7)

Here are relevant issues tracked in jackson-databind repository: FasterXML/jackson-databind#2022, FasterXML/jackson-databind#1410.

To resolve this issus either:

  • remove kind field (preferred)
  • change include = JsonTypeInfo.As.PROPERTY to EXISTING_PROPERTY

Tagged unions

Typescript-generator can generate tagged unions (#81) for Jackson polymorphic classes that uses @JsonTypeInfo annotation with include = JsonTypeInfo.As.PROPERTY.

New

Typescript-generator can now detect mentioned duplicate property issue and does not generate tagged unions for such classes. In addition to this it also logs warning.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions