Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 551
THIS USER NEEDS HELP Avatar asked Sep 27 '16 01:09

THIS USER NEEDS HELP


1 Answers

Set visible=true for @JsonTypeInfo:

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

Refer this post

like image 87
THIS USER NEEDS HELP Avatar answered Oct 13 '22 00:10

THIS USER NEEDS HELP