Reputation: 360
I have been looking around the internet to try and find the a good Java to Json library that can preserve references to objects within a java object. The two libraries I have been looking at are:
Here is some simplified code of what I want to maintain:
public class SaveMe
{
public User previous = null;
public User next = null;
}
public class User
{
public int id;
public String name;
public User(int id, String name)
{
this.id = id;
this.name = name;
}
}
Taken something like:
SaveMe saveMe = new SaveMe();
User previousAndNext = new User();
saveMe.previous = previousAndNext;
saveMe.next = previousAndNext;
In this case I have a saveMe object with the previous and next objects pointing to the same object. I am wanting to find a way to convert the object to Json, and then back again whilst maintaining that previous
and next
on the saveMe
object point to the same User
object.
I have attempted this with Gson and Jackson, but haven't found a way to properly do this. When I convert the json back into a Java object the object has two copies of the User
object in my saveMe
object, instead of just a single reference.
EDIT:
Thanks to @dnault and @StaxMan for their response. The documentation link for using @JsonIdentityInfo is great and straightforward. Is there any way to do something similar in Gson? I am a bit more familiar with Gson, and already have it implemented in my current code. I'm sure the Jackson way would work for my needs, but I'm just wondering if there is a way to do this in Gson as well.
Upvotes: 1
Views: 1218
Reputation: 116590
Jackson can do this using @JsonIdentityInfo
annotation; this is needed to enable id/reference tracking, since it is somewhat costly, and also because there are multiple ways to generate object id to use.
Link given in a comment above (http://wiki.fasterxml.com/JacksonFeatureObjectIdentity) should help; as well as this entry.
Upvotes: 1