Suren Aznauryan
Suren Aznauryan

Reputation: 1094

Jackson polymorphic deserialization using annotations

Assume we have the following types:

interface Animal {}
class Dog implements Animal {...}
class Cat implements Animal {...}
class Zoo {
    private String animalType;
    private Animal animal;
    ...
}

Having that Cat and Dog have different properties, how can we deserialize Zoo object to appropriate Animal subtype based on animalType string which is always present in json ? I know how to do that with custom deserialization but i can't find the way to do the same using Jackson annotations. This would be possible if animalType property resides in Cat or Dog but in my case its location is in Zoo.

Any idea ?

Upvotes: 1

Views: 1164

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22244

You can annotate the animal field in Zoo with JsonTypeInfo to specify which subtype you want Dog or Cat per the animalType field also in Zoo. The tricky bit is to specify that the specific type of Animal will come from a property outside of Animal in the JSON i.e. an EXTERNAL_PROPERTY

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "animalType")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
        @JsonSubTypes.Type(value = Dog.class, name = "dog")
})
private Animal animal;

Upvotes: 2

Related Questions