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

来源:互联网 发布:武器发射工程 知乎 编辑:程序博客网 时间:2024/06/15 13:19

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

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

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

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

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

0 0
原创粉丝点击