1

I have this response:

[{ "age" : "12",
    "name" : "name1"

  },
  { "age" : "21",
    "name" : "name2"

  }]

How can i parse this response using Gson

ArrayList<PersonModel> persons = gson.fromJson(response, PersonModel.class);

this will not work with me

2
  • 1
    could you add your PersonModel and which error you get? Commented Oct 16, 2016 at 11:33
  • ArrayList<PersonModel> persons = gson.fromJson(response, PersonModel.class); IDE don't let me do it like this Commented Oct 16, 2016 at 12:10

3 Answers 3

2

Since you're trying to convert your JSON array to an ArrayList of PersonModel (I'm assuming you already figured out how to write the PersonModel.class), you should use TypeToken to convert the JSON response to ArrayList.

ArrayList<PersonModel> persons = gson.fromJson(response, new TypeToken<List<PersonModel>>(){}.getType());
Sign up to request clarification or add additional context in comments.

Comments

0

the easiest way to parse this is to use PersonModel[] instead. first make a model class like this:

public class MyModel {

public PersonModel[] persons;

} 

then use it like below:

MyModel obj = gson.fromJson(response, MyModel.class)

1 Comment

I have used the answer above , your solution could work also . thank you
0

This solution is working. I just tested.

ArrayList persons = gson.fromJson(response, new TypeToken>(){}.getType());

Following solution doesn't work.

the easiest way to parse this is to use PersonModel[] instead. first make a model class like this:

public class MyModel {

public PersonModel[] persons;

} then use it like below:

MyModel obj = gson.fromJson(response, MyModel.class)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.