文章预览
前言
GSON弥补了JSON的许多不足的地方,在实际应用中更加适用于Java开发。在这里,我们主要讲解的是利用GSON来操作java对象和json数据之间的相互转换,包括了常见的对象序列化和反序列化的知识。
参考文章
https://www.jianshu.com/p/75a50aa0cad1
https://www.yiibai.com/gson/gson_overview.html
操作
1、导入依赖
implementation 'com.google.code.gson:gson:2.8.6'
2、JavaBean
2.1、user.java
package com.enjoy.gsondemo.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;
@Expose
//无法以class作为字段名
@SerializedName("class")
private int cls;
public User(String userName, String password, int age, boolean isStudent) {
this.userName = userName;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
public void setTest1(int test1) {
this.test1 = test1;
}
public void setTest2(int test2) {
this.test2 = test2;
}
public void setCls(int cls) {
this.cls = cls;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public int getAge() {
return age;
}
public boolean isStudent() {
return isStudent;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
", job=" + job +
", test1=" + test1 +
", test2=" + test2 +
", cls=" + cls +
'}';
}
}
2.2、Job.java
package com.enjoy.gsondemo.bean;
public class Job {
private String name;
private int salary;
public Job(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "Job{" +
"name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
3、对Java对象进行序列化与反序列化
@Test
public void testNestedObject() {
//java对象
User u1 = new User("zzuli", "123", 18, false);
Job job = new Job("工人", 10000);
u1.setJob(job);
//Gson提供的Gson对象
Gson gson = new Gson();
//序列化
String json = gson.toJson(u1);
System.out.println("序列化:" + json);
User u2 = gson.fromJson(json, User.class);
System.out.println("反序列化:" + u2.getUserName() + "-" + u2.getPassword() +"-"+u2.getJob());
}

4、对Aarray、List进行序列化与反序列化
package com.enjoy.gsondemo;
import com.enjoy.gsondemo.bean.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ArrayUnitTest {
@Test
public void testArray() {
User[] users1 = new User[3];
//java对象
users1[0] = new User("Lance", "123", 18, false);
users1[1] = new User("Alex", "123", 88, true);
//Gson提供的Gson对象
Gson gson = new Gson();
//序列化
String json = gson.toJson(users1);
System.out.println("序列化:"+json);
User[] users2 = gson.fromJson(json, User[].class);
System.out.println("反序列化0:"+users2[0]);
System.out.println("反序列化1:"+users2[1]);
System.out.println("反序列化2:"+users2[2]);
}
@Test
public void testListObject() {
List<User> list1 = new ArrayList<>();
list1.add(new User("Lance", "123", 18, false));
list1.add(new User("Alex", "123", 88, true));
list1.add(null);
//Gson提供的Gson对象
Gson gson = new Gson();
//序列化
String json = gson.toJson(list1);
System.out.println("序列化:"+json);
//反序列化
Type type = new TypeToken<List<User>>() {
}.getType();
List<User> list2 = gson.fromJson(json, type);
System.out.println("反序列化0:"+list2.get(0).getUserName());
System.out.println("反序列化1:"+list2.get(1));
System.out.println("反序列化2:"+list2.get(2));
}
}
Array

List

5、对Map、Set集合进行序列化与反序列化
package com.enjoy.gsondemo;
import com.enjoy.gsondemo.bean.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MapUnitTest {
@Test
public void testMap() {
Map<String, User> map1 = new HashMap<>();
//java对象
map1.put("1", new User("Lance", "123", 18, false));
map1.put("2", new User("Alex", "123", 88, true));
map1.put("3", null);
map1.put(null, null);
//Gson提供的Gson对象
Gson gson = new Gson();
//序列化
String json = gson.toJson(map1);
System.out.println(json);
Type type = new TypeToken<Map<String, User>>() {
}.getType();
Map<String, User> map2 = gson.fromJson(json, type);
System.out.println(map2.get(null));
System.out.println(map2.get("1"));
}
@Test
public void testSet() {
Set<User> set1 = new HashSet<>();
set1.add(new User("Lance", "123", 18, false));
set1.add(new User("Alex", "123", 88, true));
set1.add(null);
//Gson提供的Gson对象
Gson gson = new Gson();
//序列化
String json = gson.toJson(set1);
System.out.println(json);
//反序列化
Type type = new TypeToken<Set<User>>() {
}.getType();
Set<User> set2 = gson.fromJson(json, type);
Iterator<User> iterator = set2.iterator();
while (iterator.hasNext()) {
User next = iterator.next();
System.out.println("反序列化:" + next);
}
}
}
Map

Set

注解解释
@SerializedName注解
用于手动指定序列化的key值
@SerializedName("money")
private String salary;
@SerializedName({"money", "salary"}) // 可以有多个备选值
private String salary;
@Expose()注解
果想要让java类的某些字段不参加序列化或反序列化,可以显示来设置。如:
@Expose(serialize=false,deserialize=false)
private String name;
注意使用该注解进行序列化与反序列化需要一些列方式创建Gson对象
//Gson提供的Gson对象
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
本文详细介绍如何使用GSON库实现Java对象与JSON数据之间的序列化及反序列化操作,包括基本JavaBean类、数组、List、Map和Set等常见数据结构。

1048

被折叠的 条评论
为什么被折叠?



