2012-04-05 69 views
7

我的字符串是:GSON到deserialise名稱/值對數組

"[{"property":"surname","direction":"ASC"}]" 

我能得到GSON到deserialise這一點,而不會增加它/包裹呢? 基本上,我需要反序列化一個名稱 - 值對的數組。 我嘗試了一些方法,無濟於事。

+1

[你剛剛嘗試了什麼?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2012-04-05 17:48:04

+0

我試着定義一個集合類型,例如Type collectionType = new TypeToken >(){}。getType();也是這種方法http://stackoverflow.com/questions/9853017/parsing-json-array-with-gson – Black 2012-04-05 19:04:58

+0

解決的辦法是作爲一個自定義類型「排序」的數組進行反序列化,例如: public class Sort { 私人字符串屬性; 私人字符串方向; } Sort [] sorts = gson.fromJson(sortJson,Sort []。class); – Black 2012-04-05 20:47:46

回答

12

你基本上要代表它作爲地圖列表:

public static void main(String[] args) 
{ 
    String json = "[{\"property\":\"surname\",\"direction\":\"ASC\"}]"; 

    Type listType = new TypeToken<ArrayList<HashMap<String,String>>>(){}.getType(); 

    Gson gson = new Gson(); 

    ArrayList<Map<String,String>> myList = gson.fromJson(json, listType); 

    for (Map<String,String> m : myList) 
    { 
     System.out.println(m.get("property")); 
    } 
} 

輸出:

如果陣列中的對象含有一組已知鍵/值對,您可以創建一個POJO並映射到:

public class App 
{ 
    public static void main(String[] args) 
    { 
     String json = "[{\"property\":\"surname\",\"direction\":\"ASC\"}]"; 
     Type listType = new TypeToken<ArrayList<Pair>>(){}.getType(); 
     Gson gson = new Gson(); 
     ArrayList<Pair> myList = gson.fromJson(json, listType); 

     for (Pair p : myList) 
     { 
      System.out.println(p.getProperty()); 
     } 
    } 
} 

class Pair 
{ 
    private String property; 
    private String direction; 

    public String getProperty() 
    { 
     return property; 
    }  
}