做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);