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

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

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

  

public String list() throws Exception{
        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
        List<User> userList=userService.findEmployeeList(pageBean,s_user);
        long total=userService.getEmployeeCount(s_user);
        
        JsonConfig jsonConfig=new JsonConfig();
        jsonConfig.setExcludes(new String[]{"warehouseMainList","reWarehouseMainList","sellMainList","reSellMainList"});//去除级联关系
        //jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        //jsonConfig.registerJsonValueProcessor(User.class,new ObjectJsonValueProcessor(new String[]{"id","ename"}, User.class));
        JSONArray rows=JSONArray.fromObject(userList, jsonConfig);
        JSONObject result=new JSONObject();
            
        result.put("rows", rows);
        result.put("total", total);
        ResponseUtil.write(ServletActionContext.getResponse(), result);
        return null;
    }
原文地址:https://www.cnblogs.com/claricre/p/6732743.html