`
luoyu-ds
  • 浏览: 138315 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

There is a cycle in the hierarchy解决办法

 
阅读更多

相信大家做过JSON相关的东西对这个异常并不陌生,这个异常是由于JSONObject插件内部会无限拆解你传入的对象,直到没有可拆解为止,问题就在这,如果你传入的对象有外键关系,或者相互引用,那么内部就会死循环,也就会抛出这个异常
解决办法,我们先说一种网上通用的:过滤
     不错,过滤肯定会解决该问题,过滤也有两种方法:

     一种是通过

jsonConfig.setExcludes(new String[]{"dianYuanHeSuans"})
 

    该方法接受一个数组,也就是你需要过滤的字段,很简单就能完成。
     二种是通过

jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
			
			@Override
			public boolean apply(Object source, String name, Object value) {
				if(name.equals("qualityChecks")){
					return true;
				}
				return false;
			}
		});
 

这种方式,其实和第一种差不多,达到同样的效果,也很简单。

接下来是我主要想说的,其实这两种方法,有种弊端

假如说我们一个User对象里有个属性是部门,引用的是Organzition这个对象,如果不做任何处理,调用JSONObject.fromObject方法同样会抛出异常,如果我们通过过滤把Organzition属性过滤了,那么在前台显示的时候,将看不到有关部门的任何信息,其实需要显示也不多,比如仅一个部门名字就可以,但是过滤掉什么都没有了,这个时候,很多同学会再建一个VO类来封装前台需要的属性,这无疑增加了工作量和代码的冗余,LZ正是被该问困扰了很久,所以给出个解决办法。

 

借用JSONObject里的JsonValueProcessor接口,我们自己实现该接口,代码如下:

/**
 * 解决JSONObject.fromObject抛出"There is a cycle in the hierarchy"异常导致死循环的解决办法
 * @author LuoYu
 * @date 2012-11-23
 */
public class ObjectJsonValueProcessor implements JsonValueProcessor {
	
	/**
	 * 需要留下的字段数组
	 */
	private String[] properties;
	
	/**
	 * 需要做处理的复杂属性类型
	 */
	private Class<?> clazz;
	
	/**
	 * 构造方法,参数必须
	 * @param properties
	 * @param clazz
	 */
	public ObjectJsonValueProcessor(String[] properties,Class<?> clazz){
		this.properties = properties;
		this.clazz =clazz;
	}

	@Override
	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return "";
	}

	@Override
	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		PropertyDescriptor pd = null;
		Method method = null;
		StringBuffer json = new StringBuffer("{");
		try{
			for(int i=0;i<properties.length;i++){
				pd = new PropertyDescriptor(properties[i], clazz);
				method = pd.getReadMethod();
				String v = String.valueOf(method.invoke(value));
				json.append("'"+properties[i]+"':'"+v+"'");
				json.append(i != properties.length-1?",":"");
			}
			json.append("}");
		}catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.fromObject(json.toString());
	}
	
	
}

      在processObjectValue这个方法里重写,具体请看代码,另外在构造方法里我给出了两个参数,一个是需要留下来的属性名,通过数组传递,另一个是一个Class<?> type,也是相关上面说到例子中的Organzition.class,是用来在后面通过该class调用java反射机制获取属性值,在取到相关属值后组装成字符串,最后通过JSONObject.fromObject来输出,不这样输出会有问题,至于什么问题,有好奇心的同学自己试试

下面是调用方法:

jsonConfig.registerJsonValueProcessor(Organzition.class, 
       new ObjectJsonValueProcessor(new String[]{"orgName","orgId"},Organzition.class));
 

其中,Organzition.class是你要处理的属性类型

 

5
0
分享到:
评论
1 楼 570524053 2013-06-29  
我是用hibernate反向工程做的,里面有一个users表的反射类,你说的那个Organzition.class,是users.class?可是读取的数据是{"list":["","","","","","","",""]}

相关推荐

    json-lib出现There is a cycle in the hierarchy解决办法

    如果需要解析的数据间存在级联关系,而互相嵌套引用,在hibernate中极容易嵌套而抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。

    S2S3H3整合以及泛型Dao与Service封装

    并且对Dao和Service进行了封装,内含.jar包,并且解决了一对多双向关联的could not initialize proxy - no Session错误,同时解决了……invoked on net.sf.json.JSONException: There is a cycle in the hierarchy!...

    Android View Hierarchy,解决View Hierarchy不能启动

    解决这个启动 View Hierarchy时的这个bug: hierarchy viewer unable to debug device

    计算机组成与结构体系英文课件:Chapter 8 – The Memory System - 2

    Memory Hierarchy is a design strategy implemented to bridge the gap between the Central Processing Unit (CPU) and the various types of memory, which have differing speed, capacity, and cost ...

    A consistency improving method in the analytic hierarchy process based on directed circuit analysis

    Test of consistency is critical for the AHP methodology. When a pairwise comparison matrix (PCM) fails the consistency test, the decision maker (DM) needs to make revisions. The state of the art ...

    The Elements of Computing Systems

    the best way to understand how computers work is to build one from scratch, and this textbook leads students through twelve chapters and projects that gradually build a basic hardware platform and a ...

    WebServiceDemo-CXF-Main

    【WebServiceDemo-CXF-Main】是一个使用Apache CXF框架通过主方法(Main)来发布的Web服务示例。在本文中,我们将深入探讨Web服务、Apache CXF框架以及如何通过Java的main方法启动Web服务。 首先,让我们理解Web...

    Hierarchical_State_Machine 源代码

    Even when the actual handling differs, there is still some commonality. Hierarchical state machine design captures the commonality by organizing the states as a hierarchy. The states at the higher ...

    Hierarchy面板管理插件(Unity)

    在Unity游戏引擎中,"Hierarchy面板管理插件"是用来...两个插件都致力于解决Unity默认Hierarchy面板的局限性,提供更高效的场景管理体验。无论是独立开发者还是大型团队,这些插件都能显著提升Unity项目的开发效率。

    微软内部资料-SQL性能优化3

    An intent lock indicates that SQL Server wants to acquire a shared (S) lock or exclusive (X) lock on some of the resources lower down in the hierarchy. For example, a shared intent lock placed at the ...

    Deep learning

    co-founder and CEO of Tesla and SpaceX, Deep learning is a form of machine learning that enables computers to learn from experience and understand the world in terms of a hierarchy of concepts....

    deep learning

    co-founder and CEO of Tesla and SpaceX, Deep learning is a form of machine learning that enables computers to learn from experience and understand the world in terms of a hierarchy of concepts....

Global site tag (gtag.js) - Google Analytics