java - How to deserialize json to object using SubTypes?
问题描述
I need deserialize JSON to object depends on the type. I have the following JSON:
{
"type": "dog",
"name": "dogName"
}
and I have the following classes:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class, name = "dog"),
@JsonSubTypes.Type(value = Cat.class, name = "cat"),
})
public abstract class Animal {
@JsonProperty("type")
public String type;
public String name;
}
public class Dog extends Animal {
...
}
public class Cat extends Animal {
...
}
and when I try to deserialize all is going fine:
public class StartPdfApp {
public static void main(String[] args) throws IOException {
...
ObjectMapper mapper = new ObjectMapper();
Animal animal = mapper.readValue(json, Animal.class);
System.out.println("TYPE: " + animal.type); // always null
System.out.println("DOG: " + (animal instanceof Dog));
System.out.println("CAT: " + (animal instanceof Cat));
}
}
but when I want to get field value type
I have null
How can I fix it?
解决方案
你需要告诉 Jackson 将 type 字段传递给反序列化器,否则它只用于类型区分。这是通过注释visible
中的属性完成的。@JsonTypeInfo
另外,不确定在您的情况下是否绝对必要,但我指定类型信息以使用现有属性:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "type",
visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class, name = "dog"),
@JsonSubTypes.Type(value = Cat.class, name = "cat"),
})
public abstract class Animal {
@JsonProperty("type")
public String type;
public String name;
}
推荐阅读
- javascript - 如何获取对象中存在的对象?
- typescript - 如何使用 typescript 将 dom 元素列表添加到 webpart 列表中以进行 spfx 开发?
- react-native - React Native 中是否有任何用于屏幕录制的库?
- sqlite - SqliteConnection 的生命周期
- angular - 如何同时为多个事件编写条件?
- vue.js - 如何将 webpack 摇树功能应用到 Vue 模板的 v-if 指令?
- reactjs - 在运行时生成堆栈屏幕/堆栈屏幕名称时,如何键入检查 React Navigator 的堆栈导航路由?
- javascript - 带有 Laravel 的革命滑块
- react-redux - 如何在功能性 react-redux 组件中显示获取的数据?
- javascript - 如何使用“this”关键字传递函数