基本上我有一些Java對象,我想序列化爲JSON儘可能少的頭痛。現在我正在使用Tomcat,Jersey和Genson。Can Genson可以處理對象上的通用嵌套字段嗎?
我發現,這樣的事情不工作(這當然是一個玩具例如)與Genson:
public class Main {
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.mapOfSets = new HashMap<>();
Set<String> set0 = new HashSet<>();
set0.add("0");
Set<String> set1 = new HashSet<>();
set1.add("1");
set1.add("11");
Set<String> set2 = new HashSet<>();
set2.add("2");
set2.add("22");
set2.add("222");
mc.mapOfSets.put("set0", set0);
mc.mapOfSets.put("set1", set1);
mc.mapOfSets.put("set2", set2);
try {
String json1 = new Genson().serialize(mc.mapOfSets);
System.out.println(json1);
String json = new Genson().serialize(mc);
System.out.println(json);
} catch (TransformationException | IOException e) {
e.printStackTrace();
}
}
}
class MyClass {
public Map<String, Set<String>> mapOfSets;
}
的上面的輸出是這樣的:
{"set1":["1","11"],"set0":["0"],"set2":["2","222","22"]}
{"mapOfSets":{"empty":false}}
關於Genson的好處是我把它放在我的WebContent文件夾中,它被用來代替與澤西捆綁的任何東西 - 不需要額外的配置。如果有一種非常簡單的方法可以讓上述對象序列化爲JSON,而無需爲每個模式編寫某種類型的轉換器,我很樂意將其用於Jersey而不是Genson,但是Genson並沒有因此而失敗遠遠不足。
那麼 - 我如何按摩Genson來正確序列化 - 或者什麼是無痛處理這類事情的庫?
謝謝!
發佈完成,請參閱我的編輯 – eugen