在使用JSONObject.fromObject的时候,出现“There is a cycle in the hierarchy”异常。
意思是出现了死循环,也就是Model之间有循环包含关系;
其一:根据原理来解决,如果需要解析的数据间存在级联关系,而互相嵌套引用,在hibernate中极容易嵌套而抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。
;
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中.