java GSON 反序列化名称/值对数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10033366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GSON to deserialise array of name/value pairs
提问by Black
my string is:
我的字符串是:
"[{"property":"surname","direction":"ASC"}]"
can I get GSON to deserialise this, without adding to it / wrapping it? Basically, I need to deserialise an array of name-value pairs. I've tried a few approaches, to no avail.
我可以让 GSON 反序列化它,而不添加它/包装它吗?基本上,我需要反序列化一组名称-值对。我尝试了几种方法,都无济于事。
回答by Brian Roach
You basically want to represent it as List of Maps:
您基本上想将其表示为地图列表:
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"));
}
}
Output:
输出:
surname
姓
If the objects in your array contain a known set of key/value pairs, you can create a POJO and map to that:
如果数组中的对象包含一组已知的键/值对,则可以创建一个 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;
}
}