给定这样的 JSON:
{
"locale" : "US",
"children" : [
{
"foo" : "bar"
},
{
"foo" : "baz"
}
]
}
被映射到 Java 对象,如下所示:
public class Parent {
@JsonProperty public String getLocale() {...}
@JsonProperty public List<Child> getChildren() {...}
}
public class Child {
public void setLocale(String locale) {...}
@JsonProperty public String getFoo() {...}
}
如何使用顶层(Parent
)级别 JSON 中的值填充子实例的区域设置属性?
我想我可以在 Child
的 setLocale()
方法上使用 @JsonDeserialize(using=MyDeserializer.class)
来使用自定义序列化程序,但这不起作用(我怀疑是因为子级别的 JSON 中没有值,所以 Jackson 不知道任何应该反序列化到 locale
属性中的值)。
我希望避免为整个 Child
类编写整个自定义反序列化器,实际上该类有更多的数据需要映射。
最佳答案
如果可以接受在子对象中引用父对象,那么您可以使用 bi-directional references建立类(class)之间的父子关系。这是一个例子:
public class JacksonParentChild {
public static class Parent {
public String locale;
@JsonManagedReference
public List<Child> children;
@Override
public String toString() {
return "Parent{" +
"locale='" + locale + '\'' +
", children=" + children +
'}';
}
}
public static class Child {
@JsonBackReference
public Parent parent;
public String foo;
@Override
public String toString() {
return "Child{" +
"locale='" + parent.locale + '\'' +
", foo='" + foo + '\'' +
'}';
}
}
final static String json = "{\n" +
" \"locale\" : \"US\",\n" +
" \"children\" : [\n" +
" {\n" +
" \"foo\" : \"bar\"\n" +
" },\n" +
" {\n" +
" \"foo\" : \"baz\"\n" +
" }\n" +
" ]\n" +
"}";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Parent parent = mapper.readValue(json, Parent.class);
System.out.println("Dumping the object");
System.out.println(parent);
System.out.println("Serializing to JSON");
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(parent));
}
}
输出:
Dumping the object:
Parent{locale='US', children=[Child{locale='US', foo='bar'}, Child{locale='US', foo='baz'}]}
Serializing to JSON:
{
"locale" : "US",
"children" : [ {
"foo" : "bar"
}, {
"foo" : "baz"
} ]
}
关于java - 将 JSON 反序列化为 Java 对象时,如何将父属性映射到子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800519/