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.
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:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With