Array数组和List的序列化和反序列化

发布时间:2023年12月18日

一、前言

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

二、Array数组的序列化和反序列化

1.创建User类

public class User {
    @Expose
    private String userName;
    @Expose
    private String password;
    @Expose
    private int age;
    @Expose
    private boolean isStudent;
    @Expose
    private Job job;

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

    public int getAge() {
        return age;
    }

    public boolean isStudent() {
        return isStudent;
    }

    public void setJob(Job job) {
        this.job = job;
    }

    public Job getJob() {
        return job;
    }

    public User(String userName, String password, int age, boolean isStudent) {
        this.userName = userName;
        this.password = password;
        this.age = age;
        this.isStudent = isStudent;
    }
}

2.创建Job类


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.Array数组序列化和反序列化代码实现

public class ArrayListUnitTest {
    @Test
    public void testArray() {
        User[] user1 = new User[3];
        //创建java对象
        user1[0] = new User("Anglin1", "123", 18, false);
        user1[1] = new User("Anglin2", "123", 88, true);
        //创建Gson对象
        Gson gson = new Gson();

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

        //反序列化
        User[] user2 = gson.fromJson(json, User[].class);
        System.out.println("反序列化0:"+user2[0]);
        System.out.println("反序列化1:"+user2[1]);
        System.out.println("反序列化2:"+user2[2]);
    }
}

4.运行结果

三、List集合的序列化和反序列化

1.在原来user类和job类的基础上实现List集合的序列化和反序列化

public class ArrayListUnitTest {
 

    @Test
    public void testListObject() {
        List<User> list1 = new ArrayList<>();
        list1.add(new User("Anglin1","123",18,false));
        list1.add(new User("Anglin2","123",22,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(list2.get(0));
        System.out.println(list2.get(1));
        System.out.println(list2.get(2));
    }
}

2.运行结果

文章来源:https://blog.csdn.net/Rssqzqyp/article/details/134924543
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。