Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON object with gson

Tags:

json

android

gson

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?

like image 900
onCreate Avatar asked Feb 01 '14 20:02

onCreate


1 Answers

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
like image 138
Josh Feldman Avatar answered Oct 13 '22 06:10

Josh Feldman