Java uses GSON to parse JSON

1. Introduction to GSON

JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for humans to read and write. It is also easy for machines to parse and generate.
Gson is a Java class library provided by Google for mapping between Java objects and JSON data. You can convert a JSON string into a Java object (deserialization), or vice versa (serialization).
It's easy to use:

First, you need to import the jar package of the GSON class library into your own project,

GSON's github address: https://github.com/google/gson/

GSON download address: https://search.maven.org/artifact/com.google.code.gson/gson/2.8.6/jar

Android introduces GSON:

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

2. JavaBean serialization /deserialization

  • Serialization of JavaBean using gson object
  • Serialization of JavaBean by using gson object

2.1 Single javaBean

Create the User bean class

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 Nested classes

Create Student (name, age) on the basis of User, and add attributes (added)

    @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. Serialization/ deserialization of arrays and Lists

3.1 Serialization/deserialization of arrays

Like ordinary objects, array type objects can be serialized and deserialized by using 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 Serialization/deserialization of List collection

It should be noted that when deserializing objects of List collection type, because Java is pseudo-generic, generic erasure will make it impossible to deserialize into List<User>, and TypeToken needs to be used to complete deserialization.

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. Serialization/deserialization of Set and Map

Set collection type and Map collection type objects are the same as List when deserializing, and need to use TypeToken to complete deserialization.

4.1 Serialization/deserialization of Set collection

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 Serialization/deserialization of Map collection

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. Serialization/deserialization when variable value is null

If the value of a variable is NULL, then according to the default processing of GSON, this section is ignored

6. Variable names that control serialization/deserialization

If you want the JSON string field name not to use the variable name as the Key, for example, when the Key in the SON string exists as a keyword in Java, you can use the @SerializedName annotation to control the naming of the Key in the JSON field.

If you want to specify whether GSON participates in serialization and deserialization for certain field configurations, you can use the @Expose annotation to control, and use GsonBuilder to create Gson objects:

In addition, directly using the variable modified by the transient keyword can also prevent the variable from participating in serialization/deserialization
 

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 +
                '}';
    }
}

test:

 
    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);
    }

reference:

The use of GSON in Java_5239ZM's blog-CSDN blog_gson java

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

Java uses GSON to parse JSON - IDEA introduces jar package method_Archie_java's blog-CSDN blog_gson jar

Guess you like

Origin blog.csdn.net/gqg_guan/article/details/126663046