When I convert the ArrayList<Student>
to json object, it gives the json as follows.
[{"firstName":"Namal","lastName":"Fernando"},{"firstName":"Lakmini","lastName":"Fernando"}]
But I'm unable to create the ArrayList<Student>
again from the json string that I got. How can I do it. The problem is with providing the class of the generics type in fromJson method.
I tried following methods also but faild.
List<Student> studentsUpdated = gson.fromJson(json, new ArrayList<Student>().getClass());
List<Student> studentsUpdated = gson.fromJson(json, new ArrayList<Student>().getClass().getGenericSuperclass());
Json read / write method.
private void jsonUtil(){
List<Student> students = new ArrayList<Student>();
Student student1 = new Student();
student1.setFirstName("Namal");
student1.setLastName("Fernando");
students.add(student1);
Student student2 = new Student();
student2.setFirstName("Lakmini");
student2.setLastName("Fernando");
students.add(student2);
Gson gson = new Gson();
String json = gson.toJson(students);
System.out.println("jsonUtil().json : " + json);
List<Student> studentsUpdated = gson.fromJson(json, ArrayList<Student>.class); // This is the place that the error occured
}
Student class :
class Student{
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
String firstName = "-";
String lastName = "-";
}