I am trying to deserialize an JSON object like
{
"name":"aaa",
"children": [
{"name":"bbb"}
]
}
Into Java objects where the child has a reference to the parent object, e.g.:
public class Parent {
public String name;
public List<Child> children;
}
public class Child {
public String name;
public Parent parent;
}
// ...
new ObjectMapper().readValue(<JSON>, Parent.class);
When deserializing it like this, Child#parent will not point back to the parent object.
I read about two approaches while doing my online research, but non seems to work.
1. Adding a constructor arg to the Child class to set the parent object
public class Child {
public String name;
public Parent parent;
public Child(Parent parent) {
this.parent = parent;
}
}
When doing this I get the error:
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of `Child` (no Creators, like default construct, exist):
cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"name":"aaa","children":[{"name":"bbb"}]}"; line: 1, column: 27]
(through reference chain: Parent["children"]->java.util.ArrayList[0])
2. Using the @JsonBackReference and @JsonManagedReference annotations
public class Parent {
public String name;
@JsonBackReference
public List<Child> children;
}
public class Child {
public String name;
@JsonManagedReference
public Parent parent;
}
This fails with:
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot handle managed/back reference 'defaultReference':
back reference type (java.util.List) not compatible with managed type (Child)
at [Source: (String)"{"name":"aaa","children":[{"name":"bbb"}]}"; line: 1, column: 1]
The JavaDoc of @JsonBackReference says it cannot be applied to collections so it obviously does not work, but I wonder why there are so many examples online where it is applied to a collection.
Question How can I achieve that a child object get's its parent/owner object automatically set when the object graph is deserialized. I actually would prefer to somehow get the first approach working somehow, as it does not pollute require to pollute the classes with framework specific annotations.