`
carvin
  • 浏览: 209729 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

json-lib 解决级联解析问题

    博客分类:
  • java
阅读更多
问题解释
级联解析就是类间相互引用,比如说ClassA中有ClassB的引用,ClassB中也有ClassA的引用,这种情况在Hibernate中的双向关联会很常见。如果是这种情况,在json-lib解析的过程中,会出现net.sf.json.JSONException: There is a cycle in the hierarchy异常。

解决办法
1、采用json-lib提供的过滤字段的方法
JsonConfig config = new JsonConfig();
String[] excludeProperties = new String[]{
"propertyA","propertyB", "propertyC"
};
config.setExcludes(excludeProperties);
JSONObject jsonObject = JSONObject.fromObject(obj,config);
String jsonStr = jsonObject.toString();


2、设置JsonConfig的循环策略
JsonConfig config = new JsonConfig();
config.setIgnoreDefaultExcludes(false);       
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
JSONObject jsonObject = JSONObject.fromObject(obj,config);
String jsonStr = jsonObject.toString();

CycleDetectionStrategy 是指遇到循环解析时将采用的策略。
CycleDetectionStrategy 有如下几种取值:
LENIENT 
  Returns empty array and null object 
NOPROP 
  Returns a special object (IGNORE_PROPERTY_OBJ) 
      that indicates the entire property should be ignored 
STRICT 
  Throws a JSONException 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics