[英]How to map a parent attribute to a child object when deserializing JSON into Java objects?
Given JSON like this: 给定这样的JSON:
{
"locale" : "US",
"children" : [
{
"foo" : "bar"
},
{
"foo" : "baz"
}
]
}
being mapped to Java objects like this: 像这样映射到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() {...}
}
How can I populate the locale property of Child instances with the value that is in the JSON at the top ( Parent
) level? 如何使用顶级(
Parent
)级别的JSON中的值填充Child实例的locale属性?
I thought I might be able to use @JsonDeserialize(using=MyDeserializer.class)
on the setLocale()
method of Child
to use a custom serializer, but that's not working (I suspect because there is no value in the JSON at the Child level so Jackson doesn't know about any values that are supposed to be deserialized into the locale
property). 我以为我可能可以在
Child
的setLocale()
方法上使用@JsonDeserialize(using=MyDeserializer.class)
以使用自定义序列化程序,但这无法正常工作(我怀疑是因为Child级别的JSON中没有值)因此,杰克逊不知道应该反序列化到locale
属性中的任何值)。
I'd like to avoid having to write an entire custom deserializer for the entire Child
class, which in reality has lots more data to be mapped. 我想避免为整个
Child
类编写整个自定义反序列化器,实际上,该类有许多要映射的数据。
If it is acceptable to have a reference to a parent in a child object, then you can use bi-directional references to establish the parent-child relationship between you classes. 如果在子对象中具有对父对象的引用是可以接受的,则可以使用双向引用在类之间建立父子关系。 Here is an example:
这是一个例子:
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));
}
}
Output: 输出:
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.