• net.sf.json.JSONException: There is a cycle in the hierarchy!错误原因及解决方法


    原因:

    我们把一个对象或者集合转化成一个json字符串的时候,他会遍历每一个字段,当你对象A里面有对象B,对象B里面有对象A的时候,这时候转化的时候就会抛出net.sf.json.JSONException: There is a cycle in the hierarchy!这个异常,这时候需要我们需要写一个过滤器。

    解决办法:

    customer = customerService.findById(customer.getCust_id());
    
    		// 转成json
    		JsonConfig cfg = new JsonConfig();
    		// 这里是把关联对象剔除掉
    		cfg.setJsonPropertyFilter(new PropertyFilter() {
    			public boolean apply(Object source, String name, Object value) {
    				if (name.equals("baseDictSource") || name.equals("baseDictIndustry") || name.equals("tbUserinfoRoles")
    						|| name.equals("baseDictLevel")) {
    					return true;
    				} else {
    					return false;
    				}
    			}
    		});
    		JSONObject jsonObject = JSONObject.fromObject(customer,cfg);
    		// System.out.println(jsonArray.toString());
    		// 将JSON数据传到页面
    		try {
    			ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
    			ServletActionContext.getResponse().getWriter().println(jsonObject.toString());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}

    这里就是定义了一个过滤器,过滤掉了名称为nbaseDictSource,baseDictIndustry和tbUserinfoRoles的字段,返回true表示过滤掉这个属性,当然了,这个过滤器自身不会起到任何作用,只有在转化的时候才会用到。

  • 相关阅读:
    centos6.5升级gcc 4.4.7为最新版4.9.1
    vmware打开虚拟级断电情况下,无法找到虚拟机文件
    centos /usr/local 和/opt 安装软件你什么不同../configure --prefix=/usr...
    centos安装git
    P1207 双重回文数
    P1214 等差数列
    P1215 母亲的牛奶
    P1217 回文质数
    P3650 滑雪课程设计
    NOIP 2015[D2 T1] 跳石头
  • 原文地址:https://www.cnblogs.com/yangxianyang/p/13675634.html
Copyright © 2020-2023  润新知