jackson中使用for的@JsonTypeInfo和@JsonSubTypes註解是什麼?什麼是jackson中使用的@JsonTypeInfo和@JsonSubTypes
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);
}
我的理解是在於它還保留了具體類型的對象與實際數據一起被序列化。
什麼是我不清楚是反序列化過程中的實際優勢/收益是什麼。
除了java文檔,沒有得到任何重要的文檔。任何1請幫助這裏或提供一些相同的文檔。
也許這個答案將幫助:https://stackoverflow.com/a/31666888/751579 – davidbak
它幫助..謝謝。 – Harshit