![](/img/trans.png)
[英]Deserializing parent and child node data of json in a single java object
[英]How to map a parent attribute to a child object when deserializing JSON into Java objects?
给定这样的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实例的locale属性?
我以为我可能可以在Child
的setLocale()
方法上使用@JsonDeserialize(using=MyDeserializer.class)
以使用自定义序列化程序,但这无法正常工作(我怀疑是因为Child级别的JSON中没有值)因此,杰克逊不知道应该反序列化到locale
属性中的任何值)。
我想避免为整个Child
类编写整个自定义反序列化器,实际上,该类有许多要映射的数据。
如果在子对象中具有对父对象的引用是可以接受的,则可以使用双向引用在类之间建立父子关系。 这是一个例子:
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"
} ]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.