Json异常:HTTP Status 500 - There is a cycle in the hierarchy!

本文分析了一种常见的JSON转换异常——循环引用导致的JSONException,并提供了解决方案。具体介绍了在Java环境中,当对象间存在相互引用关系时如何通过配置JsonConfig来避免循环引用问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTTP Status 500 - There is a cycle in the hierarchy!

type Exception report

message There is a cycle in the hierarchy!

description The server encountered an internal error that prevented it from fulfilling this request.

exception

net.sf.json.JSONException: There is a cycle in the hierarchy!
    net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:73)
    net.sf.json.JSONObject._fromBean(JSONObject.java:658)
    net.sf.json.JSONObject.fromObject(JSONObject.java:182)

后台返回的是一个对象列表,将其转为json格式时发生了上面的异常。
Json陷入了一个死循环。

原因:列表list中的对象Foodstate 与另一个bean对象Foods是多对一关系,两个bean中互相引用,这就导致了json死循环异常。
Foodstate中有:private Foods foods;
Foods中有:private Set foodstates = new HashSet(0);

解决办法:将级联对象的相关属性过滤掉

   //过滤掉Foodstate中的foods
    @SuppressWarnings("unchecked")
    public String getData() {
        List<Foodstate> food = foodstateService.getData();
         JsonConfig config = new JsonConfig();
         config.setExcludes(new String[] { "foods" });
        JSONArray jsonArray = JSONArray.fromObject(food);
        System.out.println(jsonArray);
        return SUCCESS;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值