我的字符串是:
"[{"property":"surname","direction":"ASC"}]"
我可以让 GSON 反序列化它,而不添加/包装它吗?基本上,我需要反序列化一组名称-值对。我尝试了几种方法,但无济于事。
您基本上想将其表示为地图列表:
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;
}
}