2013-02-05 44 views
0

基本上我有一些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來正確序列化 - 或者什麼是無痛處理這類事情的庫?

謝謝!

+0

發佈完成,請參閱我的編輯 – eugen

回答

0

我使用Guice來處理我的依賴注入需求,這就是爲什麼我很難讓Jackson與我的Jersey項目集成。由於Genson沒有做我想做的事情,我決定再次嘗試Jackson。我試着改變了幾件事,直到它正常工作,對SO和Google嘗試了不同的建議。

而且現在下面給出的輸出預計在我的沙盒項目:

ObjectMapper mapper = new ObjectMapper(); 
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); 
mapper.getSerializationConfig().setAnnotationIntrospector(introspector); 
String jsonData = mapper.writeValueAsString(mc); 
System.out.println(jsonData); 

{"mapOfSets":{"set1":["1","11"],"set0":["0"],"set2":["2","222","22"]}} 
2

我Gensons作者。我只是檢查了一下,這是一個錯誤,仿製藥在Genson工作正常,除了這個特殊情況... 如果你可以等到明天,我會推出今晚的新版本,包含修復和一些小的新功能。完成後我會更新我的答案。

編輯修正了錯誤併發布了0.94推送給公共maven回購,它應該在幾個小時內最多可用。這裏有一些changes in this release。請嘗試並確認它是否解決了您的問題。謝謝:)

相關問題