I need deserialize JSON to object depends on the type. I have the following JSON:
{
"type": "dog",
"name": "dogName"
}
and I have the following classes:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class, name = "dog"),
@JsonSubTypes.Type(value = Cat.class, name = "cat"),
})
public abstract class Animal {
@JsonProperty("type")
public String type;
public String name;
}
public class Dog extends Animal {
...
}
public class Cat extends Animal {
...
}
and when I try to deserialize all is going fine:
public class StartPdfApp {
public static void main(String[] args) throws IOException {
...
ObjectMapper mapper = new ObjectMapper();
Animal animal = mapper.readValue(json, Animal.class);
System.out.println("TYPE: " + animal.type); // always null
System.out.println("DOG: " + (animal instanceof Dog));
System.out.println("CAT: " + (animal instanceof Cat));
}
}
but when I want to get field value type
I have null
How can I fix it?