本文记录的是如何使用Gson处理List对象数据, 包括序列化List对象以及将Json串反序列化为List对象.

首先定义一个Student类, 其属性都是基本类型, 如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Student {
private int stuNo;
private int sex;
private String name;
public Student() {
}

public Student(int stuNo, int sex, String name) {
this.stuNo = stuNo;
this.sex = sex;
this.name = name;
}
//getter & setter
......
}

接着定义List对象List对象,将该对象序列化为Json串,如下所示:

1
2
3
4
5
6
7
8
9
Gson gson = new Gson();
List<Student> students = new ArrayList<Student>();

Student student1 = new Student(1, 1, "cici");
Student student2 = new Student(2, 1, "didi");
students.add(student1);
students.add(student2);
String listStr = gson.toJson(students);
System.out.println("json_string: " + listStr);

运行该测试用例,控制台输出如下:

1
json_string: [{"stuNo":1,"sex":1,"name":"cici"},{"stuNo":2,"sex":1,"name":"didi"}]

那么如何将上述json_string反序列化为List对象呢?接着看以下示例:

1
2
3
4
5
6
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()

上述示例中控制台输出结果如下,从结果可以看出反序列化成功。

1
2
stud name: cici
stud name: didi

经过测试,对于List的复合对象(如List<HighClass>)也可使用上述方法进行序列化和反序列化。其中HighClass对象属性定义如下:

1
2
3
4
5
public class HighClass {
private int classNo;
private String adviser;
private List<Student> students;
}

目前已转行教育行业,欢迎加微信交流:CaryaLiu