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

       如果json解析的数据间存在级联关系,就会互相嵌套引用,特别在使用hibernate时容易出现这种异常,抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。

解决方法:

      1、设置JSON-LIB的Excludes让其过滤掉引起循环的字段。

JsonConfig config = new JsonConfig(); 
config.setIgnoreDefaultExcludes(false); 
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); 
config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd")); 
//只要设置这个数组,指定过滤掉哪些字段
config.setExcludes(new String[]{ "aaa", "bbb", "ccc", "ddd" }); 

       2、设置JSON-LIB的setCycleDetectionStrategy属性让其自己处理循环,缺点:当数据过于复杂时会引起数据溢出或者效率低下

JsonConfig config = new JsonConfig(); 
config.setIgnoreDefaultExcludes(false); 
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); 
config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd")); 

 

猜你喜欢

转载自freedomchx.iteye.com/blog/1835761
今日推荐