Java中GSON的使用

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. 创建JavaBean为User(String username,String password,int age,boolean isStudent)
  2. 实例化JavaBean对象user1
  3. 创建GSON对象gson
  4. 利用gson对象进行JavaBean的序列化
  5. 利用gson对象进行JavaBean的饭序列化

1.2.1 普通JavaBean 

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

1.2.2 嵌套JavaBean 

在普通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);
    }

1.3 数组和List的序列化/反序列化

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

数组类型对象和普通对象一样,使用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]);
    }

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

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

1.4 Set和Map的序列化/反序列化

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

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

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

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

    @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>() {
        }.getType(); //泛型类型,import com.google.gson.reflect.TypeToken;
        Map userMap2 = gson.fromJson(userJson, type); //反序列化
        for (Object user:userMap2.entrySet()) {
            System.out.println(user);
        }
    }

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

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

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

如果希望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);
    }

你可能感兴趣的:(android)