gson解析json串

先定义一个Java对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Student {
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

Click and drag to move

json转Java对象

1
2
3
4
5
6
public void toObject() {
// {"age":28,"name":"野猿新一"}
String json = "{\"age\":28,\"name\":\"野猿新一\"}";
Student student = new Gson().fromJson(json, Student.class);
Log.d("gson", student.toString());
}

Click and drag to move

json转List

1
2
3
4
5
6
7
8
public void toList() {
// [{"age":21,"name":"野猿新一"},{"age":22,"name":"野猿新二"},{"age":23,"name":"野猿新三"}]
String json = "[{\"age\":21,\"name\":\"野猿新一\"},{\"age\":22,\"name\":\"野猿新二\"},{\"age\":23,\"name\":\"野猿新三\"}]";
List<Student> students = new Gson().fromJson(json, new TypeToken<List<Student>>(){}.getType());
for (Student student:students) {
Log.d("gson", student.toString());
}
}

Click and drag to move