Java使用GSON对JSON进行解析

1. GSON简介

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。
Gson是Google提供的用来在Java对象和JSON数据之间进行映射的Java类库。可以将一个JSON字符串转成一个Java对象(反序列化),或者反过来(序列化)。
使用方法很简单:

首先,需要将GSON类库的jar包引入到自己的项目中,

GSON的github地址:https://github.com/google/gson/

GSON的下载地址:https://search.maven.org/artifact/com.google.code.gson/gson/2.8.6/jar

Android引入GSON:

implementation 'com.google.code.gson:gson:2.8.6'

2.JavaBean序列化/反序列化

  • 利用gson对象进行JavaBean的序列化
  • 利用gson对象进行JavaBean的饭序列化

2.1 单个javaBean

创建User  bean类

class User {

    private String firstName;
    private String lastName;
    private Student student;

    public User() {};

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public User(String firstName, String lastName,Student student) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.student = student;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    ....

}
    public void testUserBean(){
        User user = new User("name","name2");
        Gson gson = new Gson(); //创建GSON对象
 
        String userJson = gson.toJson(user); //序列化
        System.out.println("序列化:" + userJson);
 
        User user = gson.fromJson(userJson, User.class); //反序列化
        System.out.println("反序列化:" + user);
    }

2.2 嵌套的类

在User 的基础上创建Student(name,age),并添加改属性(已添加)

    @Test
    public void nestedUserBean(){
        User user1 = new User("zhangsan","lisi");
        Gson gson = new Gson(); //创建GSON对象
        Student student = new Student("liming", 18);
        user1.setJob(student);
 
        String userJson = gson.toJson(user1); //序列化
        System.out.println("序列化:" + userJson);
 
        User user2 = gson.fromJson(userJson, User.class); //反序列化
        System.out.println("反序列化:" + user2);
    }

3. 数组和List的序列化/反序列化

3.1  数组的序列化/反序列化

数组类型对象和普通对象一样,使用toJson/fromJson即可完成序列化与反序列化。

public void test(){
        User[] users1 = new User[3];
        users1[0] = new User("zhangsan","lisi");
        users1[1] = new User("lisi","wangwu");

        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].getFirstName());
        .......
    }

3.2  List集合的序列化/反序列化

List集合类型对象需要注意的是,在反序列化时因为Java是伪泛型,泛型擦除会导致无法反序列化为List<User>,需要使用TypeToken完成反序列化。

public void testList(){
        List<User> userList1 = new ArrayList<>();
        userList1.add(new User("zhangsan","lisi"));
        userList1.add(new User("lisi","wangwu"));
        Gson gson = new Gson(); //创建GSON对象

        String userJson = gson.toJson(userList1); //序列化
        System.out.println("序列化:" + userJson);

        Type type = new TypeToken<List<User>>() {}.getType(); //泛型类型,import com.google.gson.reflect.TypeToken;
        List<User> userList2 = gson.fromJson(userJson, type); //反序列化
        System.out.println("反序列化0:" + userList2.get(0).getFirstName());
        System.out.println("反序列化1:" + userList2.get(1));
    }

4. Set和Map的序列化/反序列化

Set集合类型和Map集合类型对象在反序列化时与List一样,需要使用TypeToken完成反序列化。

4.1 Set集合的序列化/反序列化

public void testSet(){
        Set<User> userSet1 = new HashSet<>();
        userSet1.add(new User("zhangsan","lisi"));
        userSet1.add(new User("lisi","wangwu"));
        Gson gson = new Gson(); //创建GSON对象

        String userJson = gson.toJson(userSet1); //序列化
        System.out.println("序列化:" + userJson);

        Type type = new TypeToken<Set<User>>() {
        }.getType(); //泛型类型,import com.google.gson.reflect.TypeToken;
        Set<User> userSet2 = gson.fromJson(userJson, type); //反序列化
        for (User user:userSet2) {
            System.out.println(user);
        }
    }

4.2 Map集合的序列化/反序列化

public void testMap(){
        Map<String,User> userMap1 = new HashMap<>();
        userMap1.put("1", new User("zhangsan","lisi"));
        userMap1.put("2",new User("lisi","wangwu"));
        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<Map<String, User>>() {
        }.getType(); //泛型类型,import com.google.gson.reflect.TypeToken;
        Map<String,User> userMap2 = gson.fromJson(userJson, type); //反序列化
        for (Object user:userMap2.entrySet()) {
            System.out.println(user);
        }
    }

5. 变量值为null时的序列化/反序列化

如果一个变量的值为NULL,那么按照GSON默认的处理为忽略这个宁段

6. 控制序列化/反序列化的变量名称

如果希望JSON字符串字段名不以变量名作为Key,比如SON字符串中的Key存在Java中的关键字时,可以借助@SerializedName注解控制JSON字段中Key的命名。

如果希望指定GSON对某些字段配置是否参与序列化与反序列化可以使用@Expose注解控制,同时使用GsonBuilder创建Gson对象:

另外直接使用transient关键字修饰的变量,也可以让该变量不参与序列化/反序列化
 

package com.atguigu.test;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

class User2 {
    @Expose
    private String username;
    @Expose
    private String pd;
    @Expose
    private int age;
    @Expose
    private boolean isStudent;

    @Expose
    private Student student;

    //serialize:是否参与序列化,deserialize是否参与反序列化
    @Expose(serialize = false,deserialize = false)
    private int test1;

    private transient int test2;

    //使用SerializedName注解可以实现以class作为字段名
    @Expose
    @SerializedName("class")
    private int clazz;

    public User2() {
    }

    public User2(String username, String password, int age, boolean isStudent) {
        this.username = username;
        this.pd= password;
        this.age = age;
        this.isStudent = isStudent;
    }

    public User2(String username, String password, int age, boolean isStudent, Student student, int test1, int test2, int clazz) {
        this.username = username;
        this.pd= password;
        this.age = age;
        this.isStudent = isStudent;
        this.student = student;
        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 pd;
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    public void setPassword(String password) {
        this.pd= 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 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 + '\'' +
                ", pd='" + pd + '\'' +
                ", age=" + age +
                ", isStudent=" + isStudent +
                ", student=" + student +
                ", test1=" + test1 +
                ", test2=" + test2 +
                ", clazz=" + clazz +
                '}';
    }
}

测试:

 
    public void tests(){
        User2 user1 = new User2("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);
 
        User2 user2 = gson.fromJson(userJson, User2.class); //反序列化
        System.out.println("反序列化:" + user2);
    }

参考:

Java中GSON的使用_5239ZM的博客-CSDN博客_gson java

https://www.jianshu.com/p/cc159151587f

Java使用GSON对JSON进行解析——IDEA引入jar包方式_Archie_java的博客-CSDN博客_gson jar

猜你喜欢

转载自blog.csdn.net/gqg_guan/article/details/126663046