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表示过滤掉这个属性,当然了,这个过滤器自身不会起到任何作用,只有在转化的时候才会用到。

posted @ 2018-12-18 20:45  AlbertYang666  阅读(194)  评论(0编辑  收藏  举报

AlbertYang