net.sf.json.JSONException: There is a cycle in the hierarchy!

今天用net.sf.json包中的JSONArray.addAll()来添加一个从数据库查出来的list集合的时候,报了 net.sf.json.JSONException: There is a cycle in the hierarchy!的错误,通过网上查资料,发现问题是由于list集合对象中的对象存在自关联(树结构,父属性和子属性引用自身)造成的。

参考该篇文章:http://www.2cto.com/kf/201303/198961.html

采用其中的第二种方法,

将原来的代码:

<pre name="code" class="java"><span style="white-space:pre">		</span>JSONArray jsArr = new JSONArray();
		jsArr.addAll(list2);
 改为: 

<span style="white-space:pre">		</span>     <span style="font-size:18px;">JSONArray jsArr = new JSONArray();
		//ClassificationTree中有属性自关联,配置JsonConfig,读取自关联
		//防止net.sf.json.JSONException: There is a cycle in the hierarchy!
		JsonConfig jsonConfig = new JsonConfig(); //建立配置文件
		jsonConfig.setIgnoreDefaultExcludes(false); //设置默认忽略
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); 
		jsArr.addAll(list2,jsonConfig);</span>
添加成功,通过打印jsArr可以看到list对象中的相关联子对象都被添加进来了。

相关文章

文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览...
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 j...
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口...
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列...
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_uni...