做SSH项目的时候,遇到一个问题,浏览器报错:
net.sf.json.JSONException: There is a cycle in the hierarchy
当使用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)
这里对一个list进行过滤,控制台输出:
[Account [id=1, login=test001, name=测试1, pass=123456], Account [id=2, login=test002, name=测试2, pass=123456]]
[{"id":1,"login":"test001"},{"id":2,"login":"test002"}]
List<Account> accountList = accountService.query();
System.out.println(accountList);
JsonConfig config = new JsonConfig();
config.setExcludes(new String[] { "name", "pass", "categories" });
String jsons = JSONArray.fromObject(accountList, config).toString();
System.out.println(jsons);
net.sf.json.JSONException: There is a cycle in the hierarchy
当使用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)
这里对一个list进行过滤,控制台输出:
[Account [id=1, login=test001, name=测试1, pass=123456], Account [id=2, login=test002, name=测试2, pass=123456]]
[{"id":1,"login":"test001"},{"id":2,"login":"test002"}]
List<Account> accountList = accountService.query();
System.out.println(accountList);
JsonConfig config = new JsonConfig();
config.setExcludes(new String[] { "name", "pass", "categories" });
String jsons = JSONArray.fromObject(accountList, config).toString();
System.out.println(jsons);
在SSH项目中遇到JavaScript错误:net.sf.json.JSONException: There is a cycle in the hierarchy。原因是对象转换为JSON字符串时存在循环引用。通过json-lib的JsonConfig设置excludes字段,过滤掉循环引用的属性(如'name', 'pass', 'categories'),成功避免了错误并输出了过滤后的JSON数据。"
112356077,10538489,STM32脉冲宽度调制PWM详解及代码配置,"['STM32开发', '嵌入式硬件', '定时器应用', 'PWM技术']
8988

被折叠的 条评论
为什么被折叠?



