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;
}