Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object graph to JSON conversion, with cycles

Tags:

java

json

How to convert a Java object graph to JSON, where the graph has circular dependencies / cycles?

like image 229
kiran Avatar asked Jan 20 '23 16:01

kiran


2 Answers

There are many open source libraries that can generate JSON. Jersey can break the circular dependencies. For others you might want to google.

  • Jersey (Use @JsonIgnore instead of @XmlTransient to break the circular dependency)
  • Gson (doesn't support circular references. there is a open defect created for this)
  • Jackson (Handle bi-directional references using declarative methods)
  • flexjson (claims it supports circular references)
like image 59
Aravind Yarram Avatar answered Jan 23 '23 05:01

Aravind Yarram


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.

like image 35
jk. Avatar answered Jan 23 '23 07:01

jk.