Parse JSON object with gson

android, gson, json

Solution

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

Problem

I'm trying to parse JSON like: ``` {"response":[123123, 1231231, 123124, 124124, 111111, 12314]} ``` With GSON, making ``` Gson gson = new GsonBuilder().create(); int[] friends = new Gson().fromJson(answer, int[].class); System.out.print(friends[0]); ``` But get `Error Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2` How to parse this numbers in array?

Original source