Whereas @jbarrueta answer is perfect, in the 2.12 version of Jackson was introduced a new long-awaited type for the @JsonTypeInfo
annotation, DEDUCTION
.
It is useful for the cases when you have no way to change the incoming json or must not do so. I'd still recommend to use use = JsonTypeInfo.Id.NAME
, as the new way may throw an exception in complex cases when it has no way to determine which subtype to use.
Now you can simply write
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
@JsonSubTypes.Type(Dog.class),
@JsonSubTypes.Type(Cat.class) }
)
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And it will produce {"name":"ruffus", "breed":"english shepherd"}
and {"name":"goya", "favoriteToy":"mice"}
Once again, it's safer to use NAME
if some of the fields may be not present, like breed
or favoriteToy
.