开发者

Java object graph to JSON conversion, with cycles

开发者 https://www.devze.com 2023-02-06 21:19 出处:网络
How to convert a Java object gra开发者_高级运维ph to JSON, where the graph has circular dependencies / cycles?There are many open source libraries that can generate JSON. Jersey can break the circular

How to convert a Java object gra开发者_高级运维ph to JSON, where the graph has circular dependencies / cycles?


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)


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消