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

采用其中的第二种方法,

将原来的代码:

		JSONArray jsArr = new JSONArray();
		jsArr.addAll(list2);
 改为:

		     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);
添加成功,通过打印jsArr可以看到list对象中的相关联子对象都被添加进来了。

你可能感兴趣的:(java编程)