net.sf.json.JSONException: There is a cycle in the hierarchy!错误解决方案

前端之家收集整理的这篇文章主要介绍了net.sf.json.JSONException: There is a cycle in the hierarchy!错误解决方案前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用hibernate容易出现该问题,主要是由于pojo类属性存在级联关系。比如说员工和部门,在员工表里面有部门属性,而在部门表里面有个员工集合,这样就存在了嵌套引用的问题了,就会抛出这个异常。

解决方法很简单,在将每个对象转为json对象的时候用setExcludes函数将级联的属性去除掉就可以了,如下面:

@H_403_11@1 //得到所有部门
@H_403_11@ 2     //返回json对象字符串
@H_403_11@ 3     public String getAllDep(){
@H_403_11@ 4         List list = deptDAO.findAll();
@H_403_11@ 5         JsonConfig config = new JsonConfig();
@H_403_11@ 6         config.setExcludes(new String[]{"emps"});//除去emps属性
@H_403_11@ 7         String json = JSONArray.fromObject(list,config).toString();
@H_403_11@ 8         return json;
@H_403_11@ 9     }
@H_403_11@10     
@H_403_11@11     //得到所有员工
@H_403_11@12     public String getAllEmp(int id){
@H_403_11@13         List list = empDAO.findByProperty("dept.deptId",id);
@H_403_11@14         JsonConfig config = new JsonConfig();
@H_403_11@15         config.setExcludes(new String[]{"dept"});//除去dept属性
@H_403_11@16         String json = JSONArray.fromObject(list,config).toString();
@H_403_11@17         return json;
@H_403_11@18     }

*********************************************第二种方法******************************************

自己写for循环把关联参数设置为null

猜你在找的Json相关文章