Domanda

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 = "-";

}
È stato utile?

Soluzione

Use below code :

 Type type = new TypeToken<ArrayList<Student>>(){}.getType();  
 List<Student> studentsUpdated = gson.fromJson(json, type); 

instead of

List<Student> studentsUpdated = gson.fromJson(json, ArrayList<Student>.class);

Altri suggerimenti

This is what I found from google docs

If the object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type) method. Here is an example for serializing and deserialing a ParameterizedType:

  Type listType = new TypeToken<List<String>>() {}.getType();
  List<String> target = new LinkedList<String>();  target.add("blah");

  Gson gson = new Gson();
 String json = gson.toJson(target, listType);
 List<String> target2 = gson.fromJson(json, listType);

You could try TypeToken

You may use TypeToken to load the json string into a custom object.

Try out this code.

List<Student> studentsUpdated = gson.fromJson(json, new TypeToken<List<Student>>(){}.getType()); 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top