加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:20:38 所属栏目:百科 来源:网络整理
导读:链接地址:http://www.blogjava.net/peiliangye/articles/372062.html jQuery调用JSON时,net.sf.json.JSONException: There is a cycle in the hierarchy! 遇到了一些问题,如hibernate延迟加载错误,这都是老掉牙的问题了,一看就知道加个lazy=flase就OK了

链接地址:http://www.blogjava.net/peiliangye/articles/372062.html

jQuery调用JSON时,net.sf.json.JSONException: There is a cycle in the hierarchy!

遇到了一些问题,如hibernate延迟加载错误,这都是老掉牙的问题了,一看就知道加个lazy=flase就OK了。想不到快要完成了又遇到了新的问题,JSON死循环,实在让人郁闷。异常如下:


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主外键关联的错,后来就想下json源代码下来看,发现大费周章都没搞到json源码,还是老办法反编译瞅瞅,发现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。

1 List<ShoppingCart>listCarts=sCartServiceImpl
2 .ShoppingCartTable(shoppingCart);
3 // 先过滤对set集合的拆解
4 JsonConfigconfig= newJsonConfig();
5 config.setJsonPropertyFilter( newPropertyFilter() {
6@Override
7publicbooleanapply(Objectarg0,Stringarg1,Objectarg2){
8if(arg1.equals("shoppingCarts")){
9returntrue;
10}
else{
11false;
12}

13}

14}
);
15 将数据转换成Json数据 16 JSONArrayjsonObject=JSONArray.fromObject(listCarts,config);
17 System.out.println(jsonObject.toString());
18

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读