2014-07-03 41 views
-1
{"myContainer" : 
    { "couldBeAnything" : [ 
          {"id":1, "name":"sb", "category":"couldBeAnything"}, 
          {"id":2, "name":"bs", "category":"couldBeAnything"} 
         ], 
     "somethingElse" : [ 
         {"id":1, "name":"sdsa","category":"somethingElse"}, 
         {"id":2, "name":"ve","category":"somethingElse"} 
         ] 
    }, 
"id" : 0 
} 

到目前爲止,我有:使用GSON轉換JSON這應該是對象的數組,而不是

Type myContainerType = new TypeToken<MyContainer>(){}.getType(); 
MyContainerType myContainerType = gson.fromJson(myJson.getValue(), myContainerType); 

public class MyContainer { 
    private int id; 
    private Map<String, List<Foo>> foo; // and foo has id, name, category 

結果,沒有錯誤,一個人口稠密ID字段,但只是一個空圖

回答

2

我認爲結構Map<String, List<Foo>>結構json是錯誤的。當你說map時,你不需要用{來包含每個鍵值。只需將整個關鍵值放在一個{}中,並用逗號分隔。例如

{ 
    "myContainer": { 
    "couldBeAnything": [ 
     { 
    "id": 1, 
    "name": "sb", 
    "category": "couldBeAnything" 
     }, 
     { 
    "id": 2, 
    "name": "bs", 
    "category": "couldBeAnything" 
     } 
    ], 
    "somethingElse": [ 
     { 
    "id": 1, 
    "name": "sdsa", 
    "category": "somethingElse" 
     }, 
     { 
    "id": 2, 
    "name": "ve", 
    "category": "somethingElse" 
     } 
    ] 
    }, 
    "id": 0 
} 

有了這個JSON它完美

public static void main(String[] args){ 
    String json = "{\"myContainer\":{\"couldBeAnything\":[{\"id\":1,\"name\":\"sb\",\"category\":\"couldBeAnything\"},{\"id\":2,\"name\":\"bs\",\"category\":\"couldBeAnything\"}],\"somethingElse\":[{\"id\":1,\"name\":\"sdsa\",\"category\":\"somethingElse\"},{\"id\":2,\"name\":\"ve\",\"category\":\"somethingElse\"}]},\"id\":0}"; 

    Map<String, List<Foo>> obj = new HashMap<String, List<Foo>>(); 
    Gson gson = new Gson(); 
    obj = gson.fromJson(json, obj.getClass()); 
    System.out.println(obj); 
} 

輸出

{id=0.0, myContainer={couldBeAnything=[{id=1.0, name=sb, category=couldBeAnything}, {id=2.0, name=bs, category=couldBeAnything}], somethingElse=[{id=1.0, name=sdsa, category=somethingElse}, {id=2.0, name=ve, category=somethingElse}]}} 

與方法的問題是場foo的命名。您的json包含名稱爲myContainer的Map<String, List<Foo>>。因此,修改您的容器類像下面,它會工作得很好:)

public class MyContainer { 
    private int id; 
    private Map<String, List<Foo>> myContainer; 
} 

現在,這將工作

Type myContainerType = new TypeToken<MyContainer>(){}.getType(); 
MyContainer myContainer = gson.fromJson(json, myContainerType); 
System.out.println(myContainer); 
+0

json的錯誤只是錯別字,這個問題是java的結構,已經更新了問題 – NimChimpsky

+0

隨着該JSON它工作正常。我的代碼更新了答案。 –

+0

恩,對,我會仔細檢查一下。也許我做了noob錯誤,因爲那是我第一次嘗試。謝謝 – NimChimpsky