我有一对多的关系,在序列化父对象列表时,JSON正是我所需要的。但是,在序列化子对象列表时,由于Jackson的JsonIdentityInfo注释的工作方式,JSON很难在我的客户端javascript / typescript代码中使用。
列表中的第一个子节点是序列化的,但它的父节点也是如此 - 其中包括几个后续子节点的列表。因此,当需要序列化列表中的第二个孩子时,杰克逊只需放置其ID,因为它已经在第一个孩子的父母的孩子列表中被序列化。
有没有办法告诉杰克逊在序列化时优先考虑顶级列表?如果有机会告诉杰克逊在潜入他们的子项目之前序列化所有顶级项目,那将是完美的。这就是我的意思:
我有一个父类:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Parent.class)
public class Parent {
public Long id;
public String name;
public Set<Kid> kids;
}
和一个儿童班:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Kid.class)
public class Kid {
public Long id;
public String name;
public Parent parent;
}
序列化父母列表非常有效:
[
{
"id": 12,
"name": "Matthew",
"kids": [
{ "id": 21, "name": "Billy", "parent": 12 },
{ "id": 22, "name": "Bobby", "parent": 12 }
]
},
{
"id": 14,
"name": "Carol",
"kids": [
{ "id": 24, "name": "Jack", "parent": 14 },
{ "id": 25, "name": "Diane", "parent": 14 }
]
}
]
序列化孩子列表给了我这个:
[
{
"id": 21,
"name": "Billy",
"parent": {
"id": 12,
"name": "Matthew",
"kids": [
21,
{ "id": 22, "name": "Bobby", "parent": 12 }
]
}
},
22,
{
"id": 24,
"name": "Jack",
"parent": {
"id": 14,
"name": "Carol",
"kids": [
24,
{ "id": 25, "name": "Diane", "parent": 14 }
]
}
},
25
]
但我真正想要的是:
[
{
"id": 21,
"name": "Billy",
"parent": {
"id": 12,
"name": "Matthew",
"kids": [ 21, 22 ]
}
},
{
"id": 22,
"name": "Bobby",
"parent": 12
},
{
"id": 24,
"name": "Jack",
"parent": {
"id": 14,
"name": "Carol",
"kids": [ 24, 25 ]
}
},
{
"id": 25,
"name": "Diane",
"parent": 14
},
]