Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY doesn’t work as expected

From Javadoc:

Inclusion mechanism similar to PROPERTY, except that property is
included one-level higher in hierarchy, i.e. as sibling property at
same level as JSON Object to type. Note that this choice can only be
used for properties
, not for types (classes). Trying to use it for
classes will result in inclusion strategy of basic PROPERTY instead.

Noticed that can only be used for properties is bolded. Source: JsonTypeInfo.As.EXTERNAL_PROPERTY.

So, you have to move all annotation from Info class to property info or setInfo method in Response class.

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type")
@JsonSubTypes(value = { @JsonSubTypes.Type(value = Type1Info.class, name = "type1"),
        @JsonSubTypes.Type(value = Type2Info.class, name = "type2") })
public void setInfo(Info info) {
    this.info = info;
}

For me, you should also remove type property from Response class. It will be generated dynamically during serialization process. In deserialization you do not need it because Jackson cares about types. Your class could look like this:

class Response {

    private String status;
    private Info info;

    //getters, setters
}

See also this question: JSON nest class data binding.

Leave a Comment