Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON to deserialise array of name/value pairs

Tags:

java

gson

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.

like image 316
Black Avatar asked Apr 05 '12 17:04

Black


1 Answers

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;
    }    
}
like image 123
Brian Roach Avatar answered Oct 16 '22 16:10

Brian Roach