【发布时间】:2016-02-17 11:50:25
【问题描述】:
我想在类 Type 上编写 json 反序列化器,这样当 Type 根据名称从给定 json 反序列化时,它会根据某些工厂方法将值(接口 Being 类型)映射到其当前实现,该工厂方法会根据名称返回正确的类名, 并在没有任何显式反序列化的情况下填充剩余的类,也没有使用 new 显式创建 TigerBeing 或 HumanBeing 的对象。
我尝试使用@jsonCreator,但我必须使用 new 初始化整个 HumanBeing 或 TigerBeing,并在构造函数中传递所有 json。我需要对进一步使用的类型进行自动映射,因为进一步的 pojo 可能非常复杂。
{type:[{
"name": "Human",
"value": {
"height":6,
"weight":100,
"languages":["spanish","english"]
}
},
{
"name":"Tiger",
"value":{
"extinct":1,
"found":["Asia", "America", "Europe", "Africa"]
}
}
]}
I have:
public class Type {
String name;
Being value;
}
public interface Being {
}
public class TigerBeing implements Being {
Integer extinct;
String[] found;
}
public class HumanBeing implement Being {
Integer height;
Integer weight;
String[] languages;
}
【问题讨论】:
-
Jackson 支持多态类型 - 请参阅此处 programmerbruce.blogspot.de/2011/05/… - 示例 4 是这样的。你可以试试。此解决方案要求您的有效负载中至少具有类型属性,该属性将有效负载限定为
TigerBeing或HumanBeing
标签: java json jackson deserialization json-deserialization