JSON解析问题:net.sf.json.JSONException: There is a cycle in the hierarchy!

时间:2022-07-28
本文章向大家介绍JSON解析问题:net.sf.json.JSONException: There is a cycle in the hierarchy!,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

异常问题

net.sf.json.JSONException: There is a cycle in the hierarchy!
	at net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:97)
	at net.sf.json.JSONObject._fromBean(JSONObject.java:657)
	at net.sf.json.JSONObject.fromObject(JSONObject.java:172)
	at net.sf.json.AbstractJSON._processValue(AbstractJSON.java:274)
	at net.sf.json.JSONObject._processValue(JSONObject.java:2655)
	at net.sf.json.JSONObject.processValue(JSONObject.java:2721)
	at net.sf.json.JSONObject.setInternal(JSONObject.java:2736)
	at net.sf.json.JSONObject.setValue(JSONObject.java:1424)
	at net.sf.json.JSONObject.defaultBeanProcessing(JSONObject.java:765)
	at net.sf.json.JSONObject._fromBean(JSONObject.java:699)
	at net.sf.json.JSONObject.fromObject(JSONObject.java:172)
	at net.sf.json.AbstractJSON._processValue(AbstractJSON.java:274)
	at net.sf.json.JSONArray._processValue(JSONArray.java:2513)
	at net.sf.json.JSONArray.processValue(JSONArray.java:2538)
	at net.sf.json.JSONArray.addValue(JSONArray.java:2525)
	at net.sf.json.JSONArray._fromCollection(JSONArray.java:1056)
	at net.sf.json.JSONArray.fromObject(JSONArray.java:123)
	at net.sf.json.AbstractJSON._processValue(AbstractJSON.java:240)
	at net.sf.json.JSONObject._processValue(JSONObject.java:2655)
	at net.sf.json.JSONObject.processValue(JSONObject.java:2721)
	at net.sf.json.JSONObject.setInternal(JSONObject.java:2736)
	at net.sf.json.JSONObject.setValue(JSONObject.java:1424)
	at net.sf.json.JSONObject.defaultBeanProcessing(JSONObject.java:765)
	at net.sf.json.JSONObject._fromBean(JSONObject.java:699)
	at net.sf.json.JSONObject.fromObject(JSONObject.java:172)
	at net.sf.json.AbstractJSON._processValue(AbstractJSON.java:274)
	at net.sf.json.JSONArray._processValue(JSONArray.java:2513)
	at net.sf.json.JSONArray.processValue(JSONArray.java:2538)
	at net.sf.json.JSONArray.addValue(JSONArray.java:2525)
	at net.sf.json.JSONArray.element(JSONArray.java:1724)
	at net.sf.json.JSONArray.add(JSONArray.java:1249)
	at net.sf.json.JSONArray.add(JSONArray.java:1245)

原因分析

由于JSONObject内部会无限拆解你传入的对象,直到没有可拆解为止,在解析bean时,出现死循环调用,即:多个Bean之间出现了相互调用。如果你传入的对象有外键关系,或者相互引用,那么内部就会死循环,也就会抛出这个异常解决办法。例如,使用Hibernate时,查询中对象存在多表依赖关联。

解决方法

结果数据中过滤去掉bean中引起死循环调用的属性:

List<DataObject> list= this.baseService.find(xxx); // 结果数据list DataObject:数据对象
		
// 自定义JsonConfig用于过滤Hibernate配置文件所产生的递归数据	
JsonConfig config = new JsonConfig();
config.setExcludes(new String[]{"a","b"}); // 指定过滤哪些字段、对象
JSONArray result = JSONArray.fromObject(list, config);