关于Gson的坑人指出:
将list转化为json
String beanListToJson = gson.toJson(list, type);
将json还原为list
List<T > objectList = gson.fromJson(resultTemp, type);
那么坑来了——List<T> list的这个T不能是Object(这里不是指语法错误)
Object有什么好处呢?
假如我有三个不一样的对象Student,Teacher,Master要放到List
list.add(student);
list.add(teacher);
list.add(master);
String beanListToJson = gson.toJson(list, type);
当你准备把json转成list的时候:
List<T > objectList = gson.fromJson(resultTemp, type);
Student student = (Student)objectList.get(0);
Teacher teacher = (Teacher)objectList.get(1);
Master master = (Master)objectList.get(2);
Duang!Duang!Duang!ClasscastException.无法强转。
那应该怎么做呢?
创一个对象People
Class People{
Private Student student;
Private Teacher teacher;
Priavate Master master
}
list.add(people);
String beanListToJson = gson.toJson(list, type);
List<People > objectList = gson.fromJson(resultTemp, type);
People people = objectList.get(0);
Student student = people.getStudent();
Teacher teacher = people.get Teacher ();
Master master = people.get Master ();
恭喜你,成功!