JSON有一个非常经典的问题:JSONException: There is a cycle in the hierarchy!俗称死循环.解决这个问题至少有三种以上的办法,总之一句话就是过滤.今天尝试着从
反射的角度来阐述和解决这个问题.
一.“反射重组(姑且这么叫吧)”
废话不多说,直接上代码.以下代码,预设有两个实体类,Company及Product,它们为一对多双向关联映射。类Product中有属性company与之关联类Company.现在,需要以
列表形式展示Product,后台以JSON格式传递数据。
1 class 2 { 3 @RequestMapping 4 @ResponseBody 5 public void getproduct(HttpServletRequest request,HttpServletResponse response,Product product) throws Exception{ 6 PageBean<Product, Product> pageBean = this.getPageBean(request); 7 pageBean.setSearchCondObj(product); 8 PageBean<Product, Product> bean = this.productService.getProduct(pageBean); 9 Map<String, Object> map=new HashMap<String, Object>(); 10 JsonConfig config = new JsonConfig(); 11 12 //屏蔽掉相关联的实体属性,以及不需要在列表中展示的属性 13 14 config.setExcludes(new String[] {"description","companyperson","comment","productitems","companycontact"}); 15 // 把列表显示需要的实体属性传过去 16 17 config.registerJsonValueProcessor(Company.class, //调用registerJsonValueProcessor构造方法,初始化参数 18 new ObjectJsonValueProcessor(new String[]{"name","id"},Company.class)); 19 20 Map<String, Object> jsonMap = new HashMap<String, Object>(); 21 jsonMap.put("total", bean.getSize()); 22 jsonMap.put("rows", bean.getSource()); 23 JSONObject result = JSONObject.fromObject(jsonMap, config); 24 this.outPrint(response, request, result.toString()); 25 } 26 }