11

I got an json array from server response:

[{"id":1, "name":"John", "age": 20},{"id":3, "name":"Tomas", "age": 29}, {"id":12, "name":"Kate", "age": 32}, ...]

I would like to use gson to convert the above json data to a Java List<Person> object. I tried the following way:

Firstly, I created a Person.java class:

public class Person{
  private long id;
  private String name;
  private int age;

  public long getId(){
     return id;
  }

  public String getName(){
     return name;
  }

  public int getAge(){
     return age;
  }
}

Then, in my service class, I did the following:

//'response' is the above json array 
List<Person> personList = gson.fromJson(response, List.class); 

for(int i=0; i<personList.size(); i++){
   Person p = personList.get(i); //java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Person
}

I got Exception java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Person . How to get rid of my problem? I just want to convert the json array to a List<Person> object. Any help?

0

1 Answer 1

24

You need to use a supertype token for the unmarshalling, so that Gson knows what the generic type in your list is. Try this:

TypeToken<List<Person>> token = new TypeToken<List<Person>>(){};
List<Person> personList = gson.fromJson(response, token.getType());

And iterate through the results as such:

for(Person person : personList) {
    // some code here
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.