Java中GSON的使用(内含源代码)
源代码下载链接地址:
https://download.csdn.net/download/weixin_46411355/87474951
目录
- Java中GSON的使用(内含源代码)
- `源代码下载链接地址:`[https://download.csdn.net/download/weixin_46411355/87474951](https://download.csdn.net/download/weixin_46411355/87474951)
- 1.1 GSON简介
- 1.2 JavaBean序列化/反序列化
- 1.2.1 步骤说明
- 普通JavaBean
- 嵌套JavaBean
- 1.3 数组和List的序列化/反序列化
- 1.3.1 数组的序列化/反序列化
- 1.3.2 List集合的序列化/反序列化
- 1.4 Set和Map的序列化/反序列化
- 1.4.1 Set集合的序列化/反序列化
- 1.4.2 Map集合的序列化/反序列化
- 1.5 Map的value为null时的序列化/反序列化
- 1.6 控制序列化/反序列化的变量名称
- 1.6.1 JavaBean
- job类
- User类
- 1.6.2 测试类以及测试效果1
- 1.6.3 测试类以及测试效果2
1.1 GSON简介
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。
Gson是Google提供的用来在Java对象和JSON数据之间进行映射的Java类库。可以将一个JSON字符串转成一个Java对象(反序列化),或者反过来(序列化)。
GSON地址:google/gson (github.com)
Android引入GSON:
implementation ‘com.google.code.gson:gson:2.9.0’
1.2 JavaBean序列化/反序列化
1.2.1 步骤说明
- 导入Gson的jar包
- 创建JavaBean为User(String username,String password,int age,boolean
isStudent) - 实例化JavaBean对象user1
- 创建GSON对象gson
- 利用gson对象进行JavaBean的序列化
- 利用gson对象进行JavaBean的反序列化
下载gson的jar包,这里笔者提供笔者的gson jar包的下载链接地址:https://download.csdn.net/download/weixin_46411355/87474404
创建一个JavaSe项目,在项目中创建一个lib目录,将这个jar包放进lib目录
鼠标右键jar包,点击Add as Library 即可
普通JavaBean
JavaBean
User.java对象
package _1JavaBean序列化和反序列化._01普通JavaBean;
import com.sun.jmx.snmp.mpm.SnmpMsgTranslator;
import java.io.Serializable;
import java.util.Objects;
public class User implements Serializable {
private String username;
private String password;
private int age;
boolean isStudent;
public User() {
}
public User(String username, String password, int age, boolean isStudent) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isStudent() {
return isStudent;
}
public void setStudent(boolean student) {
isStudent = student;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
isStudent == user.isStudent &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password);
}
@Override
public int hashCode() {
return Objects.hash(username, password, age, isStudent);
}
}
测试类
package _1JavaBean序列化和反序列化._01普通JavaBean;
import com.google.gson.Gson;
public class TestJavaBean {
public static void main(String[] args) {
User user1 = new User("zhangsan", "123", 18, false);
Gson gson = new Gson();//创建Gson对象
String userJson = gson.toJson(user1);//序列化
System.out.println("序列化:" + userJson);
User user2 = gson.fromJson(userJson, User.class);//反序列化
System.out.println("反序列化:" + user2);
}
}
测试效果
嵌套JavaBean
在普通JavaBean的基础上创建Job(String name,BigDecimal salary),并在User对象中添加Job属性
Job.java
package _1JavaBean序列化和反序列化._02嵌套JavaBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
public class Job implements Serializable {
private String name;
private BigDecimal salary;
public Job() {
}
public Job(String name, BigDecimal salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Job{" +
"name='" + name + '\'' +
", salary=" + salary +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Job job = (Job) o;
return Objects.equals(name, job.name) &&
Objects.equals(salary, job.salary);
}
@Override
public int hashCode() {
return Objects.hash(name, salary);
}
}
User.java
package _1JavaBean序列化和反序列化._02嵌套JavaBean;
import java.io.Serializable;
import java.util.Objects;
public class User implements Serializable {
private String username;
private String password;
private int age;
boolean isStudent;
private Job job;
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
public User(String username, String password, int age, boolean isStudent, Job job) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
this.job = job;
}
public User() {
}
public User(String username, String password, int age, boolean isStudent) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isStudent() {
return isStudent;
}
public void setStudent(boolean student) {
isStudent = student;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
isStudent == user.isStudent &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password);
}
@Override
public int hashCode() {
return Objects.hash(username, password, age, isStudent);
}
}
测试类
package _1JavaBean序列化和反序列化._02嵌套JavaBean;
import com.google.gson.Gson;
import java.math.BigDecimal;
public class TestNestedJavaBean {
public static void main(String[] args) {
User user1 = new User("zhangsan","123",18,false);
Gson gson = new Gson();//创建Gson对象
Job job = new Job("自有职业",new BigDecimal(2500.00));
user1.setJob(job);
String user1Json = gson.toJson(user1);//序列化
System.out.println("序列化:"+user1Json);
User user2 = gson.fromJson(user1Json, User.class);
System.out.println("反序列化:"+user2);
}
}
测试效果
1.3 数组和List的序列化/反序列化
1.3.1 数组的序列化/反序列化
数组类型对象和普通对象一样,使用toJson/fromJson即可完成序列化与反序列化。
JavaBean
User.java
package _2数组和List的序列化和反序列化._01数组的序列化和反序列化;
import java.io.Serializable;
import java.util.Objects;
public class User implements Serializable {
private String username;
private String password;
private int age;
boolean isStudent;
public User() {
}
public User(String username, String password, int age, boolean isStudent) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isStudent() {
return isStudent;
}
public void setStudent(boolean student) {
isStudent = student;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
isStudent == user.isStudent &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password);
}
@Override
public int hashCode() {
return Objects.hash(username, password, age, isStudent);
}
}
测试类
package _2数组和List的序列化和反序列化._01数组的序列化和反序列化;
import com.google.gson.Gson;
public class TestArray {
public static void main(String[] args) {
User[] users1 = new User[3];
users1[0] = new User("zhangsan","123",18,false);
users1[1] = new User("lisi","333",20,true);
Gson gson = new Gson();//创建GSON对象
String users1Json = gson.toJson(users1);//序列化
System.out.println("序列化:"+users1Json);
User[] users2 = gson.fromJson(users1Json,User[].class);//反序列化
System.out.println("反序列化0:"+users2[0].getUsername());
System.out.println("反序列化1:"+users2[1]);
System.out.println("反序列化2:"+users2[2]);
}
}
测试效果
1.3.2 List集合的序列化/反序列化
List集合类型对象需要注意的是,在反序列化时因为Java是伪泛型,泛型擦除会导致无法反序列化为List,需要使用TypeToken完成反序列化。
javabean
User.java
package _2数组和List的序列化和反序列化._02List集合的序列化和反序列化;
import java.io.Serializable;
import java.util.Objects;
public class User implements Serializable {
private String username;
private String password;
private int age;
boolean isStudent;
public User() {
}
public User(String username, String password, int age, boolean isStudent) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isStudent() {
return isStudent;
}
public void setStudent(boolean student) {
isStudent = student;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
isStudent == user.isStudent &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password);
}
@Override
public int hashCode() {
return Objects.hash(username, password, age, isStudent);
}
}
测试类
package _2数组和List的序列化和反序列化._02List集合的序列化和反序列化;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class TestList {
public static void main(String[] args) {
List<User> userList1 = new ArrayList<>();
userList1.add(new User("zhangsan", "123", 18, false));
userList1.add(new User("lisi", "333", 20, true));
Gson gson = new Gson();//创建Gson对象
String userList1Json = gson.toJson(userList1);//序列化
System.out.println("序列化:" + userList1Json);
Type type = new TypeToken<List<User>>() {
}.getType();//泛型类型,import com.google.gson.reflect.TypeToken;
List<User> userList2 = gson.fromJson(userList1Json, type);//反序列化
System.out.println("反序列化0:"+userList2.get(0).getUsername());
System.out.println("反序列化1:"+userList2.get(1));
}
}
测试结果
1.4 Set和Map的序列化/反序列化
Set集合类型和Map集合类型对象在反序列化时与List一样,需要使用TypeToken完成反序列化。
1.4.1 Set集合的序列化/反序列化
javabean
User.java
package _3Set和Map的序列化和反序列化._01Set集合的序列化和反序列化;
import java.io.Serializable;
import java.util.Objects;
public class User implements Serializable {
private String username;
private String password;
private int age;
boolean isStudent;
public User() {
}
public User(String username, String password, int age, boolean isStudent) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isStudent() {
return isStudent;
}
public void setStudent(boolean student) {
isStudent = student;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
isStudent == user.isStudent &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password);
}
@Override
public int hashCode() {
return Objects.hash(username, password, age, isStudent);
}
}
测试类
package _3Set和Map的序列化和反序列化._01Set集合的序列化和反序列化;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;
public class TestSet {
public static void main(String[] args) {
Set<User> userSet1 = new HashSet<>();
userSet1.add(new User("zhangsan","123",18,false));
userSet1.add(new User("lisi","333",20,true));
userSet1.add(null);
Gson gson = new Gson(); //创建GSON对象
String userSet1Json = gson.toJson(userSet1);//序列化
System.out.println("序列化:"+userSet1Json);
Type type = new TypeToken<Set<User>>() {
}.getType();//泛型类型,import com.google.gson.reflect.TypeToken;
Set<User> userSet2 = gson.fromJson(userSet1Json, type);//反序列化
for (User user : userSet2) {
System.out.println(user);
}
}
}
测试效果
1.4.2 Map集合的序列化/反序列化
javabean
User.java
package _3Set和Map的序列化和反序列化._02Map集合的序列化和反序列化;
import java.io.Serializable;
import java.util.Objects;
public class User implements Serializable {
private String username;
private String password;
private int age;
boolean isStudent;
public User() {
}
public User(String username, String password, int age, boolean isStudent) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isStudent() {
return isStudent;
}
public void setStudent(boolean student) {
isStudent = student;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
isStudent == user.isStudent &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password);
}
@Override
public int hashCode() {
return Objects.hash(username, password, age, isStudent);
}
}
测试类
package _3Set和Map的序列化和反序列化._02Map集合的序列化和反序列化;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class TestMap {
public static void main(String[] args) {
Map<String,User> userMap1 = new HashMap<>();
userMap1.put("1",new User("zhangsan","123",18,false));
userMap1.put("2",new User("lisi","333",20,true));
userMap1.put("3",null);
userMap1.put(null,null);
Gson gson = new Gson();//參加Gson对象
String userMap1Json = gson.toJson(userMap1);//序列化
System.out.println("序列化:"+userMap1Json);
Type type = new TypeToken<Map<String, User>>(){}.getType();//泛型类型 import com.google.gson.reflect.TypeToken;
Map<String,User> userMap2 = gson.fromJson(userMap1Json, type);//反序列化
// for (Object user : userMap2.entrySet()) {
// System.out.println(user);
// }
userMap2.entrySet().forEach(System.out::println);
}
}
测试结果
1.5 Map的value为null时的序列化/反序列化
如果一个Map的value为NULL,那么按照GSON默认的处理为忽略这个map项
1.6 控制序列化/反序列化的变量名称
如果希望JSON字符串字段名不以变量名作为Key
,比如SON字符串中的Key存在Java中的关键字时,可以借助@SerializedName注解控制JSON字段中Key的命名
。
如果希望指定GSON对某些字段配置是否参与序列化与反序列化可以使用@Expose注解控制,同时使用GsonBuilder创建Gson对象:
另外直接使用transient关键字修饰的变量,也可以让该变量不参与序列化/反序列化
之前,我们都是假设 model字段都是需要序列化和反序列化的,这是一种最简单的情况,可真实的情况并不是如此,所以我们需要定制我们的解析规则。从而引出@Expose注解。
@Expose注解
当你不需要完全序列化model字段时,我们就可以使用@Expose来帮我解决。
查看@Expose的源码如下
@Expose默认有两个属性:serialize(是否序列化) 和 deserialize(是否反序列化),默认值都为true。如果你给字段设置了@Expose注解,但是没有设置serialize和deserialize,那model的字段都将会输出。
transient
使用transient来描述字段,将不能被序列化和反序列化
@SerializedName(“XXX”)
使用@SerializedName(“XXX”)注解可以实现以"XXX"作为字段名
1.6.1 JavaBean
job类
package _4控制序列化和反序列化的变量名称;
import com.google.gson.annotations.Expose;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
public class Job implements Serializable {
@Expose
private String name;
@Expose
private BigDecimal salary;
public Job() {
}
public Job(String name, BigDecimal salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Job{" +
"name='" + name + '\'' +
", salary=" + salary +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Job job = (Job) o;
return Objects.equals(name, job.name) &&
Objects.equals(salary, job.salary);
}
@Override
public int hashCode() {
return Objects.hash(name, salary);
}
}
User类
package _4控制序列化和反序列化的变量名称;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
public class User {
@Expose
private String username;
@Expose
private String password;
@Expose
private int age;
@Expose
private boolean isStudent;
@Expose
private Job job;
//serialize:是否参与序列化,deserialize是否参与反序列化
@Expose(serialize = false,deserialize = false)
private int test1;
//使用transient来描述字段,将不能被序列化和反序列化
private transient int test2;
//使用@SerializedName("class")注解可以实现以"class"作为字段名
@Expose
@SerializedName("class")
private int clazz;
public User() {
}
public User(String username, String password, int age, boolean isStudent) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
public User(String username, String password, int age, boolean isStudent, Job job, int test1, int test2, int clazz) {
this.username = username;
this.password = password;
this.age = age;
this.isStudent = isStudent;
this.job = job;
this.test1 = test1;
this.test2 = test2;
this.clazz = clazz;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isStudent() {
return isStudent;
}
public void setStudent(boolean student) {
isStudent = student;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
public int getTest1() {
return test1;
}
public void setTest1(int test1) {
this.test1 = test1;
}
public int getTest2() {
return test2;
}
public void setTest2(int test2) {
this.test2 = test2;
}
public int getClazz() {
return clazz;
}
public void setClazz(int clazz) {
this.clazz = clazz;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
", job=" + job +
", test1=" + test1 +
", test2=" + test2 +
", clazz=" + clazz +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
isStudent == user.isStudent &&
test1 == user.test1 &&
test2 == user.test2 &&
clazz == user.clazz &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password) &&
Objects.equals(job, user.job);
}
@Override
public int hashCode() {
return Objects.hash(username, password, age, isStudent, job, test1, test2, clazz);
}
}
1.6.2 测试类以及测试效果1
package _4控制序列化和反序列化的变量名称.test;
import _4控制序列化和反序列化的变量名称.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class TestVariableNameOfControllSerializeAndDeserialize {
public static void main(String[] args) {
User user1 = new User("zhangsan","123",18,false);
user1.setTest1(1);
user1.setTest2(2);
user1.setClazz(3);
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();//让@Expose注解生效
String user1Json = gson.toJson(user1);//序列化
System.out.println("序列化:"+user1Json);
User user2 = gson.fromJson(user1Json, User.class);
System.out.println("反序列化:"+user2);
}
}
测试效果
1.6.3 测试类以及测试效果2
package _4控制序列化和反序列化的变量名称.test;
import _4控制序列化和反序列化的变量名称.Job;
import _4控制序列化和反序列化的变量名称.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.math.BigDecimal;
public class TestVariableNameOfControllSerializeAndDeserialize02 {
public static void main(String[] args) {
User user1 = new User("zhangsan","123",18,false);
user1.setTest1(1);
user1.setTest2(2);
user1.setClazz(3);
Job job = new Job("Java开发",new BigDecimal(10000.00));
user1.setJob(job);
Gson gson =new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();//让@Expose注解生效
String user1Json = gson.toJson(user1);//序列化
System.out.println("序列化:"+user1Json);
User user2 = gson.fromJson(user1Json, User.class);//反序列化
System.out.println("反序列化:"+user2);
}
}
测试效果