`
carvin
  • 浏览: 214985 次
  • 性别: 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 
分享到:
评论

相关推荐

    JSON-RPC for Java使用说明1

    JSON-RPC for Java是用于Java平台的一个轻量级、零入侵的远程过程调用(RPC)框架,特别适合于AJAX应用中的级联调用。本文档将详细介绍如何在Java项目中使用JSON-RPC,包括引入依赖库、创建服务类、自定义基类以及在...

    JQuery + Servlet +Json实现下拉框级联

    4. **部署和测试**:将Servlet配置到服务器,确保JQuery库和json-lib-2.4-jdk15.jar在项目类路径中,然后在浏览器中运行HTML页面,测试下拉框级联的功能。 总的来说,通过JQuery、Servlet和JSON的结合,我们可以...

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

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

    关于jquery(ajax)web四级联动

    在项目中,我们会用到两个外部库:fastjson-1.1.33.jar用于JSON数据解析,以及mysql-connector-java-5.1.37-bin.jar作为MySQL数据库连接驱动。这两个JAR文件需要添加到项目的类路径(Classpath)中,对于Eclipse,...

    springMVC+Hibernater整合及测试(亲测可运行)所需jar包

    同时,Hibernate还支持二级缓存,事务管理,以及对象关系映射的高级特性,如懒加载、级联操作等。 在Spring MVC和Hibernate的整合中,通常会使用Spring的声明式事务管理,这样可以在Controller层无需显式管理事务,...

Global site tag (gtag.js) - Google Analytics