What are @JsonTypeInfo and @JsonSubTypes used for in jackson

前端 未结 1 1076
轮回少年
轮回少年 2020-12-25 12:04

What are @JsonTypeInfo and @JsonSubTypes annotations using for in jackson ?

public class Lion extends Animal {

private String name;

@JsonCreator
public Li         


        
相关标签:
1条回答
  • 2020-12-25 12:28

    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.

    0 讨论(0)
提交回复
热议问题