3
Given the classes below, we need to solve the problem of infinite recursion (cyclic dependency) and, for this, we use @Jsonidentityinfo, from Jackson 2+:
@JsonIdentityInfo(scope=Parent.class, generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
@Getter
@Setter
public class Parent {
private Long id;
private String nome;
private List<Child> filhos;
}
@JsonIdentityInfo(scope=Child.class, generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
@Getter
@Setter
@AllArgsConstructor
public class Child {
private Long id;
private Parent pai;
private String nome;
}
We are having trouble converting the above entities to JSON. In fact, converting Parent objects occurs as expected ...
{
"id":1,
"nome":"PAI1",
"filhos":[
{
"id":10,
"pai":1,
"nome":"FILHO1"
},
{
"id":11,
"pai":1,
"nome":"FILHO2"
}
]
}
... however, this is not the case when trying to convert Child objects individually or in lists ...
individual:
{
"id":10,
"pai":{
"id":1,
"nome":"PAI1",
"filhos":[
10,
{
"id":11,
"pai":1,
"nome":"FILHO2"
}
]
},
"nome":"FILHO1"
}
list:
[
{
"id":10,
"pai":{
"id":1,
"nome":"PAI1",
"filhos":[
10,
{
"id":11,
"pai":1,
"nome":"FILHO2"
}
]
},
"nome":"FILHO1"
},
11
]
... we hoped that the individual would have the attribute children as null and that the list would also have them as null, besides returning only objects, and not object/id, as occurred...
expected individual result:
{
"id":10,
"pai":{
"id":1,
"nome":"PAI1",
"filhos":null (ou [])
},
"nome":"FILHO1"
}
expected list result: list:
[
{
"id":10,
"pai":{
"id":1,
"nome":"PAI1",
"filhos":null (ou [])
},
"nome":"FILHO1"
},
{
"id":11,
"pai":{
"id":1,
"nome":"PAI1",
"filhos":null (ou [])
},
"nome":"FILHO2"
}
]
Below is the main executed method that returns the above result:
public static void main(String[] args) throws IOException {
Parent pai = new Parent();
pai.setId(1L);
pai.setNome("PAI1");
List<Child> filhos = new ArrayList<Child>();
filhos.add(new Child(10L, pai, "FILHO1"));
filhos.add(new Child(11L, pai, "FILHO2"));
pai.setFilhos(filhos);
System.out.println(new ObjectMapper().writeValueAsString(pai));
System.out.println(new ObjectMapper().writeValueAsString(filhos));
System.out.println(new ObjectMapper().writeValueAsString(filhos.get(0)));
}