Reputation: 120268
Let's say I have a parent child relationship. My Parent json looks like
{
childrens: [...]
}
Let's say the model I want to (de)serialize to/from has an intermediate object between the parent and children.
class Parent {
Intermediate intermediate
}
class Intermediate {
Child[] children;
}
Can I configure Jackson to create that intermediate object when deserializing the json into the model, and similarly skip the intermediate object when serializing back to json?
Upvotes: 0
Views: 313
Reputation: 4657
You can use the @JsonUnwrapped
annotation for this case. Here is an example with a similar structure to your post
Parent.java
import com.fasterxml.jackson.annotation.JsonUnwrapped;
public class Parent {
@JsonUnwrapped
private Intermediate intermediate;
public Intermediate getIntermediate() {
return intermediate;
}
public void setIntermediate(Intermediate intermediate) {
this.intermediate = intermediate;
}
}
Intermediate.java
public class Intermediate {
private Child[] children;
public Child[] getChildren() {
return children;
}
public void setChildren(Child[] children) {
this.children = children;
}
}
Child.java
public class Child {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Example document
{
"children": [
{
"name": "Foo",
"age": 20
},
{
"name": "Bar",
"age": 22
}
]
}
Test Driver
ObjectMapper mapper = new ObjectMapper();
Parent parent = mapper.readValue(json, Parent.class);
for (Child child : parent.getIntermediate().getChildren()) {
System.out.println("Child: " + child.getName() + " is " + child.getAge() + " years old.");
}
Which produces the following output:
Child: Foo is 20 years old.
Child: Bar is 22 years old.
Upvotes: 1