Java 具有jackson序列化/反序列化的多级polymophic树
是否可以使用jackson序列化和反序列化复杂的继承结构?它的注释是什么?例如,如果我有以下课程Java 具有jackson序列化/反序列化的多级polymophic树,java,json,inheritance,serialization,jackson,Java,Json,Inheritance,Serialization,Jackson,是否可以使用jackson序列化和反序列化复杂的继承结构?它的注释是什么?例如,如果我有以下课程 @Inheritance @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = Dog.class,name = "dog") @Type(value =
@Inheritance
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@Type(value = Dog.class,name = "dog")
@Type(value = Cat.class,name = "cat")
})
public class Animal implements Serializable{
@id
long id;
String name;
}
这当然是父类。我知道这是正确的,如果猫和狗没有任何继承类。如果我想要狗的子类,我需要在动物类和狗类中改变什么
这是第二节课,仅供参考
@JsonTypeName("dog")
public class Dog extends Animal implements Serializable{
//all my props etc here
{
我如何创建一个从动物和狗继承的retriever类和yorki类,我可以将它们任意一个投给它们,让jackson不会对我发火。多级多态树不应该是jackson的问题。下面是一个序列化/反序列化类层次结构的示例,类似于您在问题中遇到的问题
如果没有帮助,请提供更多代码。多级多态树不应该是Jackson的问题。下面是一个序列化/反序列化类层次结构的示例,类似于您在问题中遇到的问题 如果没有帮助,请提供更多代码
public class JacksonPolymorphism3 {
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
public abstract static class Animal {
public final String animalField;
@JsonCreator
public Animal(@JsonProperty("animalField") String animalField) {
this.animalField = animalField;
}
}
@JsonTypeName("dog")
public static class Dog extends Animal {
public final String dogField;
public Dog(@JsonProperty("animalField") String animalField,
@JsonProperty("dogField") String dogField) {
super(animalField);
this.dogField = dogField;
}
@Override
public String toString() {
return "Dog{" +
"dogField='" + dogField + '\'' +
'}';
}
}
@JsonTypeName("husky")
public static class Husky extends Dog {
public final String huskyField;
public Husky(@JsonProperty("animalField") String animalField,
@JsonProperty("dogField") String dogField,
@JsonProperty("huskyField") String huskyField) {
super(animalField, dogField);
this.huskyField = huskyField;
}
@Override
public String toString() {
return "Husky{" +
"huskyField='" + huskyField + '\'' +
'}';
}
}
public static void main(String[] args) throws IOException {
List<Dog> dogs;
dogs = Arrays.asList(new Dog("aField", "dogField"), new Husky("hField", "dField2", "hField"));
ObjectMapper mapper = new ObjectMapper();
mapper.registerSubtypes(Dog.class, Husky.class);
TypeReference<List<Dog>> referenceType = new TypeReference<List<Dog>>() {
};
String json = mapper.writerWithDefaultPrettyPrinter().withType(referenceType).writeValueAsString(dogs);
System.out.println(json);
System.out.println(mapper.readValue(json, referenceType));
}
}
[ {
"type" : "dog",
"animalField" : "aField",
"dogField" : "dogField"
}, {
"type" : "husky",
"animalField" : "hField",
"dogField" : "dField2",
"huskyField" : "hField"
} ]
[Dog{dogField='dogField'}, Husky{huskyField='hField'}]