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

net.sf.json.JSONException: There is a cycle in the hierarchy!
        at net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.
handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:97)
        at net.sf.json.JSONObject._fromBean(JSONObject.java:674)
        at net.sf.json.JSONObject.fromObject(JSONObject.java:181)
        at net.sf.json.JSONArray._processValue(JSONArray.java:2381)
        at net.sf.json.JSONArray.processValue(JSONArray.java:2412)
        Truncated. see log file for complete stacktrace
>


仔细查了一下发现是hibernate主外键关联的错,JSONArray根据判断取得的不同类型调用相应的方法,

if (object instanceof Collection)
    return _fromCollection((Collection)object, jsonConfig);

而我从hibernate那得到的是list,所以去调用了_fromCollection方法,而里面的方法发现一个问题:该方法会不断的拆开实体属性,直到没有为止,而我的ContactGroup里有两个属性用于自身关联

private Set contactGroups = new HashSet(0);
private Set contactGroupPersons = new HashSet(0);


也就是说主外键自身关联的是个死循环,那怎么才能不让他出现这种情况呢,应该有个配置的参数后者终止循环的地方吧,查看发
现,jsonConfig,呵呵,config应该是配置参数吧,参看JsonConfig看见巨多的属性,有点晕PropertyFilter 
,不提了,看了老半天,发现了一个属性PropertyFilter,PropertyFilter 是一个interface,代码如下:


public interface PropertyFilter
{


public abstract boolean apply(Object obj, String s, Object obj1);
}


也就是说我可以通过这个方法过滤掉List里的相应属性,只要让它返回true就可过滤掉,……,有点悬……我们重写一下这个方法:


JsonConfig cfg = new JsonConfig();
    cfg.setJsonPropertyFilter(new PropertyFilter()
    {
         public boolean apply(Object source, String name, Object value) {
           if(name.equals("contactGroups")||name.equals("contactGroupPersons")) {
             return true;
           } else {
             return false;
          }
        }
       });

将hibernate产生的实体bean中的contactGroups和contactGroupPersons过滤掉就OK了!

然后调用JSONArray.fromObject(mychildren,cfg); mychildren是hibernate返回的list。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值