I have a one-to-many relationship, and when serializing a list of the parent objects, the JSON is exactly what I need. However when serializing a list of the the child objects, the JSON is tough to work with in my client side javascript/typescript code because of the way Jackson's JsonIdentityInfo annotation works.
What happens is the first child in the list is serialized, but so is its parent - which includes a list of several of the subsequent children. So when it comes time to serialize the second child in the list, Jackson simply places its ID, since it was already serialized in the first child's parent's list of children.
Is there a way to tell Jackson to prioritize the top level list when serializing? If there was way to tell Jackson to serialize all top level items before diving into their sub items, that would be perfect. Here's what I mean:
I have a parent class:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Parent.class)
public class Parent {
public Long id;
public String name;
public Set<Kid> kids;
}
And a child class:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Kid.class)
public class Kid {
public Long id;
public String name;
public Parent parent;
}
Serializing a list of parents works perfectly:
[
{
"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 }
]
}
]
Serializing a list of children gives me this:
[
{
"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
]
But what I really want is this:
[
{
"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
},
]