Reputation: 87
How to convert a Java object graph to JSON, where the graph has circular dependencies / cycles?
Upvotes: 4
Views: 4828
Reputation: 36
Not sure about what you mean by circular dependencies, JSON has no possibility to express references. There are a lot of opensource JSON lib's do check out the link http://x-stream.github.io/json-tutorial.html for converting java object to JSON
Upvotes: 0
Reputation: 7696
Note: this answer was written a long time ago. Use Gson, Jersey or Jackson.
I went with json-simple on my last project. It doesn't bring in any unneeded project dependencies (such as apache-commons jars) and was enough to parse/generate JSON correctly.
You'll still have to manage circular references yourself. I really doubt there is such a library that is built to handle this. You can do this easily by added to a Set any objects that you convert, and then just checking to see if the object you're about to convert is in the set.
Also, I don't think json-simple automatically serializes an object; that is, you have to feed it the data you want added to the JSON. It just handles all of the messy formatting for you.
Upvotes: 2
Reputation: 3028
if you using fasterxml . there is new and call option @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
. checkout this for more info
just make sure your fasterxml in at the right version for that
Upvotes: 0
Reputation: 80194
There are many open source libraries that can generate JSON. Jersey can break the circular dependencies. For others you might want to google.
Upvotes: 7