[原创]json-lib 出现net.sf.json.JSONException: There is a cycle in the hier_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 2126 | 回复: 0   主题: [原创]json-lib 出现net.sf.json.JSONException: There is a cycle in the hier        下一篇 
panpan.nie
注册用户
等级:大校
经验:4754
发帖:217
精华:2
注册:1970-1-1
状态:离线
发送短消息息给panpan.nie 加好友    发送短消息息给panpan.nie 发消息
发表于: IP:您无权察看 2016-2-24 11:08:02 | [全部帖] [楼主帖] 楼主


错误信息:

net.sf.json.JSONException: There is a cycle in the hierarchy!

blob.png


错误原因:

    model a里面包含了b,而model b里面又包含了a,这样造成了解析成对象的过程中的死循环

如:Hibernate中设置了自身关联:

<set name="desc" inverse="true">
    <key>
        <column name="mid" not-null="true" />
    </key>
    <one-to-many class="Desc"/>
</set>


如果还是需要保留这种关系,可以使用json-lib提供的JsonConfig把循环的属性在转换的过程中忽略掉:

JsonConfig config = new JsonConfig();
config.setExcludes(new String[]{"desc"});
String json = JSONArray.fromObject(userList, config).toString();


当然,还有如下的方法可以实现属性的排除:

实现JSONString接口:(排除了desc)

public class User implements JSONString {  
   private String name;  
   private String password;  
   private String desc;  
   // getters & setters  
   public String toJSONString() {  
      return "{name:'"+name+"', password:'"+password+"'}";  
   }  
}


设置JsonConfig的propertyFilter过滤属性:

public class User {  
   private String name;  
   private String password;  
   private String desc;  
   // ...  
}  
JsonConfig jsonConfig = new JsonConfig();  
jsonConfig.setJsonPropertyFilter( new PropertyFilter(){  
   public boolean apply( Object source, String name, Object value ){  
      return source instanceof User && name.equals("desc");  
   }  
});  
User user = new User();  
JSON json = JSONSerializer.toJSON( user, jsonConfig )


写一个自定义的JsonBeanProcessor方法:

public class User {  
   private String name;  
   private String password;  
   private String desc;  
   // ...  
}  
JsonConfig jsonConfig = new JsonConfig();  
jsonConfig.registerJsonBeanProcessor( User.class,  
   new JsonBeanProcessor(){  
      public JSONObject processBean( Object bean, JsonConfig jsonConfig ){  
         if( !(bean instanceof User) ){  
            return new JSONObject(true);  
         }  
         User user = (user) bean;  
         return new JSONObject()  
            .element( "name", user.getName() )  
            .element( "password", user.getPassword() );  
      }  
});  
User user = new User();  
JSON json = JSONSerializer.toJSON( user, jsonConfig );





赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论