10

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.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
Black
  • 5,023
  • 6
  • 63
  • 92
  • 1
    [What *exactly* have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Brian Roach Apr 05 '12 at 17:48
  • I tried defining a collection type, eg Type collectionType = new TypeToken>(){}.getType(); and also this approach http://stackoverflow.com/questions/9853017/parsing-json-array-with-gson – Black Apr 05 '12 at 19:04
  • The solution is to deserialise as an array of custom type 'Sort', e.g: public class Sort { private String property; private String direction; } Sort[] sorts = gson.fromJson(sortJson, Sort[].class); – Black Apr 05 '12 at 20:47

1 Answers1

18

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;
    }    
}
Brian Roach
  • 76,169
  • 12
  • 136
  • 161