假设我有以下类(class):
public class Parent {
public int age;
@JsonUnwrapped
public Name name;
}
生成 JSON:
{
"age" : 18,
"first" : "Joey",
"last" : "Sixpack"
}
如何将其反序列化回 Parent 类?我可以使用@JsonCreator
@JsonCreator
public Parent(Map<String,String> jsonMap) {
age = jsonMap.get("age");
name = new Name(jsonMap.get("first"), jsonMap.get("last"));
}
但这也有效地将 @JsonIgnoreProperties(ignoreUnknown=true)
添加到 Parent 类,因为所有属性都映射到这里。因此,如果您希望未知的 JSON 字段引发异常,则必须自己进行。此外,如果映射值可能不是字符串,则必须进行一些手动类型检查和转换。 jackson 有没有办法自动处理这个案子?
编辑:
我可能疯了,但这实际上似乎有效,尽管文档中从未明确提及:http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html
我很确定它以前对我不起作用。尽管如此,当需要自定义逻辑来反序列化解包的多态类型时,建议的 @JsonCreator 方法可能更受欢迎。
最佳答案
您可以为每个字段使用 @JsonCreator
和 @JsonProperty
:
@JsonCreator
public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
@JsonProperty("lastName") String lastName) {
this.age = age;
this.name = new Name(firstName, lastName);
}
在这种情况下,Jackson 会为您进行类型检查和未知字段检查。
关于java - @JsonUnwrapped 的 Jackson 反序列化等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16570073/