0

I have the following class:

class Person 
{
    String Name; 
}

I read in the following Json data:

{
    "People": [{
            "Name": "Test"
        },
        {
            "Name": "Hello"
        }
    ]
}

I do this using a generic class as these could be students, professors etc..

public BusinessData<T> GetDataFromJson(String Url)
{
    // Get the data from the URL 
    return new Gson().fromJson(data, new TypeToken<BusinessData<T>>(){}.getType());
}

public List<People> GetPeople()
{
      return this.GetDataFromJson(Url).People;
}

Therefore.. I should now have a List of the class People.. However, whenever I try and do the following:

for(People person : PeopleList)
{
    System.out.println(person.getName());  
}

I get the following error:

com.google.gson.internal.LinkedTreeMap cannot be cast to com.proj.business.Models.Person

Which to me makes no sense, because:

  1. I pass in List<People> to the method I'm trying to use the data with just fine

  2. If I just do a standard System.out.println(people.get(1)) then the data is printed out just fine in the class Person

Can anyone please suggest what I am doing wrong here?

Phorce
  • 4,424
  • 13
  • 57
  • 107

2 Answers2

-1

Problem is you are getting an array of People, first cast from Array to List

DavElsanto
  • 289
  • 1
  • 4
  • 14
-1

here:

public class Test {


    public Test() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) throws Exception {



        Person personA = new Person("David");
        Person personb = new Person("Pedro");

        Person[] arrayPeople = {personA, personb};
        List<Person> listPeople = Arrays.asList(arrayPeople);
        for(Person x: listPeople)
            System.out.println(x.getName());


    }





}

class Person{
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Person() {
        // TODO Auto-generated constructor stub
    }
    public Person(String name) {
        super();
        this.name = name;
    }

}
DavElsanto
  • 289
  • 1
  • 4
  • 14