【发布时间】:2016-09-22 06:33:53
【问题描述】:
我想做的事
我想用Jackson反序列化一个多态类型,使用标准的@JsonTypeInfo注解如下:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = As.EXISTING_PROPERTY,
property = "identifier")
@JsonSubTypes({@Type(value = A.class, name = "A"),
@Type(value = B.class, name = "B")})
abstract Class Base {}
Class A implements Base {
public String identifier = "A";
}
Class B implements Base {
public String identifier = "B";
}
Class Decorated {
public String decoration = "DECORATION";
@JsonUnwrapped
public Base base;
}
/*
Serialized instance of Decorated WITHOUT @JsonUnwrapped:
{
"decoration" : "DECORATION",
"base" : {
"identifier" : "A"
}
}
Serialized instance of Decorated WITH @JsonUnwrapped:
{
"decoration" : "DECORATION",
"identifier" : "A"
}
*/
这通常可以由 Jackson 反序列化,如下所示:
public Object deserialize(String body, Class clazz) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(body, clazz);
}
(如果 @JsonUnwrapped 注释被删除,这将起作用)
问题
多态类型不能很好地与 Jackson 的 @JsonUnwrapped 注释配合使用,正如 2012 年的这张 Jira 票中所讨论的那样:
http://markmail.org/message/pogcetxja6goycws#query:+page:1+mid:pogcetxja6goycws+state:results
使用@JsonUnwrapped 处理多态类型
同意 - 虽然修复问题显然更可取,但如果无法做到,改进错误消息将很有用。
解包是实现变得足够复杂以至于出现的任何错误(尤其是反序列化)往往具有抗生素抗性的功能之一...
很难令人鼓舞。
三年后:
http://markmail.org/message/cyeyc2ousjp72lh3
使用@JsonUnwrapped 处理多态类型
解决方案:不会修复
该死的。
那么,有什么方法可以在不修改 deserialize() 或删除 @JsonUnwrapped 注释的情况下诱使 Jackson 给我这种行为?
【问题讨论】:
-
您是否设法解决了这个问题或找到了解决方法?
-
我没有,不。在编写“装饰”字段后,您始终可以实现一个自定义序列化程序,将 Base 的序列化委托给 Jackson。
标签: java jackson polymorphism deserialization