简体   繁体   English

Java对象图到JSON转换,带循环

[英]Java object graph to JSON conversion, with cycles

如何将Java对象图转换为JSON,其中图形具有循环依赖/循环?

There are many open source libraries that can generate JSON. 有许多开源库可以生成JSON。 Jersey can break the circular dependencies. 泽西岛可以打破循环依赖。 For others you might want to google. 对于其他人,您可能想要谷歌。

Note: this answer was written a long time ago. 注意:这个答案是很久以前写的。 Use Gson, Jersey or Jackson. 使用Gson,Jersey或Jackson。

I went with json-simple on my last project. 我在上一个项目中使用了json-simple It doesn't bring in any unneeded project dependencies (such as apache-commons jars) and was enough to parse/generate JSON correctly. 它不会引入任何不需要的项目依赖项(例如apache-commons jar),并且足以正确解析/生成JSON。

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. 您可以通过添加到Set转换的任何对象,然后只是检查您要转换的对象是否在集合中来轻松完成此操作。

Also, I don't think json-simple automatically serializes an object; 另外,我不认为json-simple会自动序列化一个对象; that is, you have to feed it the data you want added to the JSON. 也就是说,您必须将要添加到JSON的数据提供给它。 It just handles all of the messy formatting for you. 它只是为您处理所有混乱的格式。

if you using fasterxml . 如果你使用fastxml。 there is new and call option @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id") 有新的和调用选项@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class,property =“@ id”)

. checkout this for more info 结帐以获取更多信息

just make sure your fasterxml in at the right version for that 只需确保你的quickxml版本正确

Not sure about what you mean by circular dependencies, JSON has no possibility to express references. 不确定你的循环依赖是什么意思,JSON没有可能表达引用。 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 有很多开源JSON lib做了检查链接http://x-stream.github.io/json-tutorial.html将java对象转换为JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM