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'
public void testJavaBean(){
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的基础上创建Job(String name,int salary),并在User对象中添加Job属性
@Test
public void testNestedJavaBean(){
User user1 = new User("zhangsan","123",18,false);
Gson gson = new Gson(); //创建GSON对象
Job job = new Job("个人", 2500.00);
user1.setJob(job);
String userJson = gson.toJson(user1); //序列化
System.out.println("序列化:" + userJson);
User user2 = gson.fromJson(userJson, User.class); //反序列化
System.out.println("反序列化:" + user2);
}
数组类型对象和普通对象一样,使用toJson/fromJson即可完成序列化与反序列化。
@Test
public void testArray(){
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 userJson = gson.toJson(users1); //序列化
System.out.println("序列化:" + userJson);
User[] users2 = gson.fromJson(userJson, User[].class); //反序列化
System.out.println("反序列化0:" + users2[0].getUsername());
System.out.println("反序列化1:" + users2[1]);
System.out.println("反序列化2:" + users2[2]);
}
List集合类型对象需要注意的是,在反序列化时因为Java是伪泛型,泛型擦除会导致无法反序列化为List
,需要使用TypeToken完成反序列化。
@Test
public void testList(){
List 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 userJson = gson.toJson(userList1); //序列化
System.out.println("序列化:" + userJson);
Type type = new TypeToken>() {
}.getType(); //泛型类型,import com.google.gson.reflect.TypeToken;
List userList2 = gson.fromJson(userJson, type); //反序列化
System.out.println("反序列化0:" + userList2.get(0).getUsername());
System.out.println("反序列化1:" + userList2.get(1));
}
Set集合类型和Map集合类型对象在反序列化时与List一样,需要使用TypeToken完成反序列化。
@Test
public void testSet(){
Set 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 userJson = gson.toJson(userSet1); //序列化
System.out.println("序列化:" + userJson);
Type type = new TypeToken>() {
}.getType(); //泛型类型,import com.google.gson.reflect.TypeToken;
Set userSet2 = gson.fromJson(userJson, type); //反序列化
for (User user:userSet2) {
System.out.println(user);
}
// Type type1 = new TypeToken>() {
// }.getType();
// Set userSet3 = gson.fromJson(userJson, type); //反序列化
// for (User user:userSet3) {
// System.out.println(user);
// }
}
@Test
public void testMap(){
Map 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 userJson = gson.toJson(userMap1); //序列化
System.out.println("序列化:" + userJson);
Type type = new TypeToken
如果一个变量的值为NULL,那么按照GSON默认的处理为忽略这个宁段
如果希望JSON字符串字段名不以变量名作为Key,比如SON字符串中的Key存在Java中的关键字时,可以借助@SerializedName注解控制JSON字段中Key的命名。
如果希望指定GSON对某些字段配置是否参与序列化与反序列化可以使用@Expose注解控制,同时使用GsonBuilder创建Gson对象:
另外直接使用transient关键字修饰的变量,也可以让该变量不参与序列化/反序列化
User.java代码
package com.example.mygson.bean;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
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;
private transient int test2;
//使用SerializedName注解可以实现以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 +
'}';
}
}
JavaBeanUnitTest.java单元代码
@Test
public void tests(){
User user1 = new User("zhangsan","123",18,false);
user1.setTest1(1);
user1.setTest2(2);
user1.setClazz(3);
// Gson gson = new Gson(); //创建GSON对象
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); //让@Expose注解生效
String userJson = gson.toJson(user1); //序列化
System.out.println("序列化:" + userJson);
User user2 = gson.fromJson(userJson, User.class); //反序列化
System.out.println("反序列化:" + user2);
}