我想做什么
我想使用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将JSON反序列化为多态类型-完整示例出现编译错误
通常可以通过以下方式使用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 给我提供此行为?