json:There is a cycle in the hierarchy!

本文介绍在使用JSONObject.fromObject方法时遇到“Thereisacycleinthehierarchy”异常的原因及解决方案,通过设置CycleDetectionStrategy.LENIENT策略防止自包含,避免死循环问题。

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

在使用JSONObject.fromObject的时候,出现“There is a cycle in the hierarchy”异常。

意思是出现了死循环,也就是Model之间有循环包含关系;

解决办法:

使用setCycleDetectionStrategy防止自包含

代码:

JsonConfig jsonConfig = new JsonConfig();

jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

JSONObject json =JSONObject.fromObject(model, jsonConfig);

result = json.toString();

 

依赖的包: 

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

 

完整实列

/** 
    * 这里测试如果含有自包含的时候需要CycleDetectionStrategy 
    */  
   public static void testCycleObject() {  
       CycleObject object = new CycleObject();  
       object.setMemberId("yajuntest");  
       object.setSex("male");  
       JsonConfig jsonConfig = new JsonConfig();  
       jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
  
       JSONObject json = JSONObject.fromObject(object, jsonConfig);  
       System.out.println(json);  
   }  
  
   public static void main(String[] args) {  
              JsonTest.testCycleObject();  
   }  

其中 CycleObject.java

public class CycleObject {  
  
    private String      memberId;  
    private String      sex;  
    private CycleObject me = this;  
…… // getters && setters  
} 

 

转载于:https://www.cnblogs.com/hwaggLee/p/4667832.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值