Type studentType = new TypeToken<List<Student>>() {}.getType(); List<Student> students2 = gson.fromJson(listStr, studentType); for (Iterator<Student> iterator = students2.iterator(); iterator.hasNext();) { Student student = (Student) iterator.next(); System.out.println("stud name: " + student.getName()); }
关于TypeToken,请看文档说明:
1 2 3 4 5 6 7 8
public abstract class TypeToken<T> extends java.lang.Object
Represents a generic type T. You can use this class to get the generic type for a class. For example, to get the generic type for Collection<Foo>, you can use:
Type typeOfCollectionOfFoo = new TypeToken<Collection<Foo>>(){}.getType()