63

What are the @JsonTypeInfo and @JsonSubTypes annotations used for in Jackson?

public class Lion extends Animal {

private String name;

@JsonCreator
public Lion(@JsonProperty("name") String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public String getSound() {
    return "Roar";
}

public String getType() {
    return "carnivorous";
}

public boolean isEndangered() {
    return true;
}

@Override
public String toString() {
    return "Lion [name=" + name + ", getName()=" + getName() + ", getSound()=" + getSound() + ", getType()=" + getType() + ", isEndangered()="
            + isEndangered() + "]";
}

}

========================================

public class Elephant extends Animal {

@JsonProperty
private String name;

@JsonCreator
public Elephant(@JsonProperty("name") String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public String getSound() {
    return "trumpet";
}

public String getType() {
    return "herbivorous";
}

public boolean isEndangered() {
    return false;
}

@Override
public String toString() {
    return "Elephant [name=" + name + ", getName()=" + getName() + ", getSound()=" + getSound() + ", getType()=" + getType()
            + ", isEndangered()=" + isEndangered() + "]";
}
}

==============================================

@JsonTypeInfo (use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "classNameExtenral")
@JsonSubTypes ({@Type (value = Lion.class, name = "lion"), @Type (value = Elephant.class, name = "elephant")})

public abstract class Animal {

@JsonProperty ("name")
String name;
@JsonProperty ("sound")
String sound;
@JsonProperty ("type")
String type;
@JsonProperty ("endangered")
boolean endangered;
}

public static void main(String[] args){
    Lion lion = new Lion("Simba");
    Elephant elephant = new Elephant("Manny");
    List<Animal> animals = new ArrayList<>();
    animals.add(lion);
    animals.add(elephant);
}

What I understand is that it additionally preserves the concrete type of object being serialised along with the actual data.

What is not clear to me is what is the actual advantage/gain during deserialization.

Not getting any significant documentation apart from the java docs. Can anyone please help out here or provide some docs around the same.

2

1 Answer 1

76

The purpose of these annotations is to support polymorphism on deserialization. When deserializing the actual code being executed will know the class of what it expects. E.g., the type of some field being deserialized into. But if that class has subclasses (i.e., subtypes) how does the generic Jackson deserializer know which actual class the string being deserialized is? It's got to create an instance of some concrete type (the class or one of its subclasses) and fill it up. The only way it can know which one to create is if that information is written into the serialization in the first place.

As this answer says there are three ways to do it - you pick the one that's appropriate for your use case. @JsonTypeInfo + @JsonSubtypes is one of those ways - it works great when you know, at compile time, all of the possible subtypes that could exist for the class in question.

3
  • 1
    Doesn't using @JsonTypeInfo on the individual concrete classes makes more sense? Using it over the interface seem to violate the open-close principle i suppose (as in we need to modify our interface on every new addition of a concrete implementation). Please correct me if am missing something here
    – Harshit
    Aug 1, 2017 at 22:02
  • Again, it depends on the use case. For example, I had a use case where I could in fact use @JsonSubtypes in one place and that was preferable to tagging each subtype. But TBH I forget what that use case was now; I do recall it was a bit out of the ordinary. But it had more to do with practical deployment/release issues than pure O-O theory. (Remember: any "principle" like open-close is just a strong guideline ... you may find in some instances that violating such a principle is correct design - just make sure you really know why.)
    – davidbak
    Aug 1, 2017 at 23:10
  • 4
    Consider you have a class Cage which contains a field of type Animal. When the Cage object is deserialized from JSON, Jackson finds that it should create an Animal, so if Animal is not annotated with @JsonTypeInfo, Jackson won't apply the support for polymorphism, and so it will create just Animal (if possible) and not its subtype. Sep 4, 2017 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.