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

14 篇文章 0 订阅

原文地址IT宅

当使用json-lib在Java中把对象转换为JSON字符串时易产生的错误,主要的原因是出现了如下的情形:

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

net.sf.json.JSONException: There is a cycle in the hierarchy!
    at net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:97)

如果还是需要保留这种关系,可以使用json-lib提供的JsonConfig把循环的属性在转换的过程中忽略掉
JsonConfig config = new JsonConfig();
config.setExcludes(new String[]{"department"});
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+"'}";  
     <span style="color:#ff9900;"> //也可以这样
      JSONObject json = new JSONObject();
      json.put("specialProjectName", specialProject==null?"":specialProject.getName());
      return json.toString();</span>
   }  
}
设置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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值