Reputation: 32924
Given JSON like this:
{
"locale" : "US",
"children" : [
{
"foo" : "bar"
},
{
"foo" : "baz"
}
]
}
being mapped to Java objects like this:
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?
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).
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.
Upvotes: 0
Views: 4963
Reputation: 10853
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"
} ]
}
Upvotes: 3