[b]问题解释[/b]
级联解析就是类间相互引用,比如说ClassA中有ClassB的引用,ClassB中也有ClassA的引用,这种情况在Hibernate中的双向关联会很常见。如果是这种情况,在json-lib解析的过程中,会出现net.sf.json.JSONException: There is a cycle in the hierarchy异常。
[b]解决办法[/b]
1、采用json-lib提供的过滤字段的方法
2、设置JsonConfig的循环策略
CycleDetectionStrategy 是指遇到循环解析时将采用的策略。
CycleDetectionStrategy 有如下几种取值:
级联解析就是类间相互引用,比如说ClassA中有ClassB的引用,ClassB中也有ClassA的引用,这种情况在Hibernate中的双向关联会很常见。如果是这种情况,在json-lib解析的过程中,会出现net.sf.json.JSONException: There is a cycle in the hierarchy异常。
[b]解决办法[/b]
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