以嵌套方式使用多个@JsonSubType注释
来源:爱站网时间:2022-12-21编辑:网友分享
本篇文章给大家讲述的是以嵌套方式使用多个@JsonSubType注释内容,有想法了解下的朋友一定要看看,在这里提供了一些思路给朋友们阅读,希望这篇文章能帮助到你们处理问题。
问题描述
是否可以嵌套使用多个@JsonSubType
注释?
例如,设想以下类别:
@Data
@JsonSubTypeInfo(include=As.EXISTING_PROPERTY, property="species", use=Id.NAME, visible=true)
@JsonSubTypes({
@Type(name="Dog", value=Dog.class)
@Type(name="Cat", value=Cat.class)
})
public abstract class Animal {
private String name;
private String species;
}
@Data
@JsonSubTypeInfo(include=As.EXISTING_PROPERTY, property="breed", use=Id.NAME, visible=true)
@JsonSubTypes({
@Type(name="Labrador", value=Labrador.class)
@Type(name="Bulldog", value=Bulldog.class)
})
public abstract class Dog {
private String breed;
}
@Data
public class Labrador extends Dog {
private String color;
}
@Data
public class Bulldog extends Dog {
private String type; // "frenchy", "english", etc..
}
如果使用对象映射器,我可以成功地将Bulldog
映射到JSON,但是,当尝试读取生成的JSON并将其读回时,会出现类似以下的错误:
Can not construct instance of com.example.Dog abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
是否有可能让Jackson进行此类分型?我需要为每个子类创建一个自定义反序列化器吗?
思路:
如果我使用@JsonTypeInfo
和与您类似的设置,则以下工作。也许您的问题出在反序列化代码中,所以请查看以下内容:以嵌套方式使用多个@JsonSubType注释
public class MyTest {
@Test
public void test() throws IOException {
final Bulldog bulldog = new Bulldog();
bulldog.setBreed("Bulldog");
bulldog.setType("B-Dog");
final ObjectMapper om = new ObjectMapper();
final String json = om.writeValueAsString(bulldog);
final Dog deserialized = om.readValue(json, Dog.class);
assertTrue(deserialized instanceof Bulldog);
}
@JsonTypeInfo(include = As.EXISTING_PROPERTY, property = "species", use = Id.NAME, visible = true)
@JsonSubTypes({
@Type(name = "Dog", value = Dog.class),
@Type(name = "Cat", value = Cat.class)
})
public static abstract class Animal {
private String name;
private String species;
}
@JsonTypeInfo(include = As.EXISTING_PROPERTY, property = "breed", use = Id.NAME, visible = true)
@JsonSubTypes({
@Type(name = "Labrador", value = Labrador.class),
@Type(name = "Bulldog", value = Bulldog.class)
})
public static abstract class Dog {
private String breed;
public String getBreed() {
return breed;
}
public void setBreed(final String breed) {
this.breed = breed;
}
}
public static abstract class Cat {
private String name;
}
public static class Labrador extends Dog {
private String color;
public String getColor() {
return color;
}
public void setColor(final String color) {
this.color = color;
}
}
public static class Bulldog extends Dog {
private String type; // "frenchy", "english", etc..
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
}
}
以嵌套方式使用多个@JsonSubType注释的详细内容都看明白了吗,想获取更多知识点的朋友一定要来本网站,我们每天都会不定时更新文章, 为你提供优质的学习内容。