When serialising object graphs with circular dependencies to JSON you need to somehow cope with it to prevent the JSON from being infinitely large. Jackson provides functionality to track the identity of objects and uses references as soon as an object is to be serialised a second time, see for example
here
Consider a list of the following classes is being serialised
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class FooBar
{
public String foo;
}
If the same object is present in the list multiple times, this results in the following serialised JSON string
[
{
"@id": 1,
"foo":"bar"
},
{
"@id": 2,
"foo":"baz"
},
1 //reference to the object with @id = 1
]
When you are in a strongely typed environment where you know the structure of the objects you want to have deserialised from this JSON, this is not a problem. If you don't know the structure, however, there is the problem that you have no idea which items are references and which are simple integers, right?
Now, a very simple solution would be to have the JSON look like this:
[
{
"@id": 1,
"foo":"bar"
},
{
"@id": 2,
"foo":"baz"
},
{
"@ref":1
}
]
This way you can simply go through your whole object graph and check for each object if it has a member `@ref`, if so you replace it with the corresponding object.
I want to generate JSON which looks like the second example. Has anyone done this already? If not, would the correct starting point be a custom
ObjectIdGenerator or a custom Serializer?