不积跬步,无以至千里;不积小流,无以成江海。要沉下心来,诗和远方的路费真的很贵!
参考博客:小胡老师的博客
JSON解析第三方框架——Gson使用
Gson概念
Gson
是谷歌官方推出的支持JSON
和Java Object
相关转换的开源Java
库。
Gson
主要用于JSON
数据结构的解析,类似的框架还有FastJson
。
Gson使用
- 在
build.gradle
中引人依赖包
implementation 'com.google.code.gson:gson:2.7' //gson
- 使用前都需要初始化
Gson
Gson gson = new Gson();
Gson将序列化对象转换为JSON格式
- 新建一个可序列化对象
/**
* @author created by lvjunkai
* @date 2021-10-30
* @description: 学生类的描述
*/
public class Student {
//成员变量
public int sno;
public String name;
public int age;
public boolean isFemale;
//构造方法
public Student(int sno, String name, int age, boolean isFemale) {
this.sno = sno;
this.name = name;
this.age = age;
this.isFemale = isFemale;
}
}
- 使用
Gson
框架将对象转换为Json
格式
//使用构造方法初始化一个新的对象
Student student = new Student(1,"KG",20,false);
//初始化Gson
Gson gson = new Gson();
//使用gson的toJson方法将对象转换为Json格式
String res = gson.toJson(student);
System.out.println(res);
Gson解析JSON对象
- 就以上述新建的
JSON
对象为例,进行解析。
//使用构造方法初始化一个新的对象
Student student = new Student(1,"KG",20,false);
//初始化Gson
Gson gson = new Gson();
//使用gson的toJson方法将对象转换为Json格式
String res = gson.toJson(student);
System.out.println(res);
//按照Student对象的格式,将JSON数据转换为Student对象
Student s = gson.fromJson(res,Student.class);
System.out.println("id:" + s.sno + ",name:" + s.name + ",age:" + s.age + ",女?" + s.isFemale);
Gson解析JSON数组
JSON数组
结构格式:采用[]
表示数组,里面全部都是value
,中间用,
隔开。
["KG", "JK", "KH", "KZ"]
- 解析
JSON
数组
//构造JSON数组
String res = "[\"KG\", \"JK\", \"KH\", \"KZ\"]";
//初始化Gson
Gson gson = new Gson();
//按照JSON数组中value的类型,将JSON数据转换为对应的类型
String[] name = gson.fromJson(res,String[].class);
//遍历数组
for(int i=0;i<name.length;i++){
//测试转换后数据
System.out.println("第" + (i+1) + "个名字:" + name[i]);
}
Gson解析List
List
其实从大致来讲,也是一个数组,只是其中的对象可以是自定义的对象,即可以是一个类。而不只是基本数据类型和String
等。就相当于数组中的value
是对象。
[{
"sno": 1,
"name": "KG",
"age": 20,
"isFemale": false
}, {
"sno": 2,
"name": "JK",
"age": 20,
"isFemale": false
}, {
"sno": 3,
"name": "KH",
"age": 20,
"isFemale": false
}, {
"sno": 4,
"name": "KZ",
"age": 20,
"isFemale": false
}]
//构造JSON数组,内容为Student对象
String res = "[{\n" +
" \"sno\": 1,\n" +
" \"name\": \"KG\",\n" +
" \"age\": 20,\n" +
" \"isFemale\": false\n" +
"}, {\n" +
" \"sno\": 2,\n" +
" \"name\": \"JK\",\n" +
" \"age\": 20,\n" +
" \"isFemale\": false\n" +
"}, {\n" +
" \"sno\": 3,\n" +
" \"name\": \"KH\",\n" +
" \"age\": 20,\n" +
" \"isFemale\": false\n" +
"}, {\n" +
" \"sno\": 4,\n" +
" \"name\": \"KZ\",\n" +
" \"age\": 20,\n" +
" \"isFemale\": false\n" +
"}]";
//初始化Gson
Gson gson = new Gson();
//得到将要解析成为的类型
Type studentListType = new TypeToken<ArrayList<Student>>(){}.getType();
//根据得到的类型,将JSON数据转换为对应的类型
List<Student> students = gson.fromJson(res,studentListType);
//和数组一样,遍历链表
for(int i=0;i<students.size();i++){
//得到每一个对象
Student student = students.get(i);
System.out.println("第" + (i+1) + "个学生信息:" + student.sno + "," + student.name +
"," + student.age + "," + student.isFemale);
}
总结
总体复习一遍,以上就是大部分经常可以看见的Gson
解析JSON
格式,基本可以涵盖所有了。