Johan
Johan

Reputation: 40588

Avoid duplicate field generated by JsonTypeInfo in Jackson

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?

Upvotes: 4

Views: 1381

Answers (2)

Bruno Shimada
Bruno Shimada

Reputation: 41

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

Upvotes: 4

beresfordt
beresfordt

Reputation: 5222

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"}

Upvotes: -2

Related Questions