Parse JSON object with gson

You're going to want to create a model class first that GSON can bind your json to:

public class ResponseModel {

    private List<Integer> response = new ArrayList<Integer>();

    public List<Integer> getResponse() {
        return response;
    }

    @Override
    public String toString() {
        return "ResponseModel [response=" + response + "]";
    }
}

Then you can call

Gson gson = new Gson();
ResponseModel responseModel = gson.fromJson("{\"response\":[123123, 1231231, 123124, 124124, 111111, 12314]}",
                                            ResponseModel.class);
List <Integer> responses = responseModel.getResponse();
// ... do something with the int list

The other option you have outside of using a wrapper class is simply to get the array from the parse tree.

Use the JsonParser to create the tree, get your array from it, then convert to int[] using Gson:

public class App 
{
    public static void main( String[] args ) throws IOException
    {
       String json = "{\"response\":[1,2,3,4,5]}";

       JsonObject jo = new JsonParser().parse(json).getAsJsonObject();
       JsonArray jsonArray = jo.getAsJsonArray("response");

       int[] myArray = new Gson().fromJson(jsonArray, int[].class);

       System.out.println(Arrays.toString(myArray));

    }
}

Note that you could also just work with the JsonArray directly and not convert it to an int[] depending on your use case.

System.out.println(jsonArray.get(0).getAsInt());

Tags:

Json

Android

Gson