使用 json-lib 序列化物件時,若物件之間存在雙向參照,就可能出「There is a cycle in the hierarchy」的錯誤。以下提供兩種解決方式。
透過 JsonConfig 的 setExcludes 指定要排除的欄位名稱,讓序列化時跳過這些會引發循環的屬性:
JsonConfig config = new JsonConfig();
config.setIgnoreDefaultExcludes(false);
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd")); //date processor register
config.setExcludes(new String[]{//只要設置這個數組,指定過濾哪些字段。
"consignee",
"contract",
"coalInfo",
"coalType",
"startStation",
"balanceMan",
"endStation"
});
String tempStr = "{\"TotalRecords\":"+ total.toString() +",\"Datas\":"+JSONSerializer.toJSON(list,config).toString()+"}";
out.print(tempStr);設定 setCycleDetectionStrategy 屬性,讓函式庫自己處理循環參照。這種做法比較省事,但如果資料結構過於複雜,可能會造成資料溢出或效率低落:
JsonConfig config = new JsonConfig();
config.setIgnoreDefaultExcludes(false);
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd")); //date processor register
String tempStr = "{\"TotalRecords\":"+ total.toString() +",\"Datas\":"+JSONSerializer.toJSON(list,config).toString()+"}";
out.print(tempStr);實務上,若你的物件關聯明確、可以清楚指出哪些欄位會造成循環,方法一會是效能與可控性都比較好的選擇;反之若想快速解決、資料又不算太複雜,方法二會更輕鬆。