json-lib 解决级联解析问题

[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提供的过滤字段的方法

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值