Jackson's @JsonTypeInfo(use = Id.CUSTOM, include = As.PROPERTY, property = "type") reads all fields of JSON except for "type"

THIS USER NEEDS HELP picture THIS USER NEEDS HELP · Sep 27, 2016 · Viewed 8.9k times · Source

I stepped through each line of code, but I think it's how Jackson handles polymorphism internally.

Using the classic example of Dog and Cat extending Animal:

@JsonTypeInfo(use = Id.CUSTOM, include = As.PROPERTY, property = "type")
@JsonTypeIdResolver(AnimalTypeIdResolver.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class Animal implements Serializable {
    public AnnotatorBundleConfig(String name) {
        super();
        this.name = name;
    }

The dog class :

public class DogAnimal extends Animal {
    @JsonCreator
    public DogAnimal(
        @JsonProperty(value="name", required=true) String name,
        @JsonProperty(value="bark_decibel") int bark_decibel)
    {
    super(name);
    this.bark_decibel = bark_decibel;}

The cat class:

public class CatAnimal extends Animal {
    @JsonCreator
    public CatAnimal(
        @JsonProperty(value="name", required=true) String name,
        @JsonProperty(value="meow_level") int meow_level)
    {
    super(name);
    this.meow_level = meow_level;}

The AnimalTypeIdResolver is a typical TypeIdResolver that extends AbstractTypeIdResolver.

For some very odd reason, bark_decibel and meow_level are deserialized from JSON, but type is getting in as null. Any ideas?

Answer

THIS USER NEEDS HELP picture THIS USER NEEDS HELP · Sep 27, 2016

Set visible=true for @JsonTypeInfo:

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

Refer this post