2012-04-05 70 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; 
    }  
}