在使用JSONObject.fromObject的时候,出现“There is a cycle in the hierarchy”异常。
意思是出现了死循环,也就是Model之间有循环包含关系;
其一:根据原理来解决,如果需要解析的数据间存在级联关系,而互相嵌套引用,在hibernate中极容易嵌套而抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200220200549398.png
User.java
UserAction
由于查询user时实体类里面有一个属性saleVisits,这是一个SaleVisits实体类的集合对象,里面存在visit_user_id属性,数据间存在级联关系,而互相嵌套引用,在hibernate中极容易嵌套而抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。
解决方案
1 .设置JSON-LIB让其过滤掉引起循环的字段:
//解决死循环
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"roles","saleVisits"});
// 将返回结果转成json
String json = JSONArray.fromObject(list, jsonConfig).toString();
2.设置JSON-LIB的setCycleDetectionStrategy属性让其自己处理循环,省事但是数据过于复杂的话会引起数据溢出或者效率低下。
JsonConfig jsonConfig = new JsonConfig(); //建立配置文件
jsonConfig.setIgnoreDefaultExcludes(false); //设置默认忽略
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
JSONArray jsonArray = JSONArray.fromObject(list,jsonConfig); //加载配置文件
return null;
3.最为原始的办法,自己写个JavaBean,用forEach循环,添加到List中.