使用jsonConfig對 object進行過濾

做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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章