使用jsonConfig對 object進行過濾
阿新 • • 發佈:2019-01-04
做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);