4

I'm using Jackson Databind 2.7.2 and I have the following annotations on an interface:

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = SubType1.class, name = "SubType1"),
        @JsonSubTypes.Type(value = SubType2.class, name = "SubType2")})
public interface Common {
     String getType();
}

getType is overridden (implemented) in SubType1 and SubType2. The problem is that when an instance of SubType1 or SubType2 is mapped to JSON it contain two fields called type with the same value:

{
  "type" : "SubType1",
  ... // Other properties
  "type" : "SubType1"
}

How can I prevent jackson from rendering duplicate fields?

Johan
  • 37,479
  • 32
  • 149
  • 237

2 Answers2

3

If anyone happens to have this error, it can be solved by changing the default include property

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.EXISTING_PROPERTY,
    visible = true,
    property = "type"
)

By default Jackson uses JsonTypeInfo.As.PROPERTY

Reference: https://fasterxml.github.io/jackson-annotations/javadoc/2.4/com/fasterxml/jackson/annotation/JsonTypeInfo.As.html

-1

Jackson renders type one time because you have told it to in the JsonTypeInfo annotation, then it renders it again because it sees a getter so it works its magic on getType() and adds another property. If you put a @JsonIgnore on the method in the interface it'll render it once:

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = SubType1.class, name = "SubType1"),
        @JsonSubTypes.Type(value = SubType2.class, name = "SubType2")})
public interface Common {
     @JsonIgnore
     String getType();
}

Produces:

{"type": "SubType1"}
beresfordt
  • 5,088
  • 10
  • 35
  • 43