欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

序列化工具-Gson-序列化和反序列化用法

程序员文章站 2024-03-16 09:44:52
...

一、环境依赖:

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.6</version>
</dependency>

二、序列化&反序列化:

public class GsonSerializer implements IGsonSerializer {
    @Override
    public <T> byte[] serialize(T obj) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(obj).getBytes();
    }
    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        Gson gson = new Gson();
        return (T)gson.fromJson(new String(data), clazz);
    }
}
public class TestMain {
    public static void main(String[] args) {
        Student stu=new Student();
        stu.setName("jason");
        stu.setAge(18);
        IGsonSerializer serializer=new GsonSerializer();
        long t1 = System.nanoTime();
        byte[] serialize = serializer.serialize(stu);
        System.out.println("序列化耗时="+(System.nanoTime()-t1));
        System.out.println("Gson 序列化长度 result="+serialize.length);
        System.out.println(""+new String(serialize));
        long t3 = System.nanoTime();
        Student stu2=(Student)(Student)serializer.deserialize(serialize,stu.getClass());
        System.out.println("反序列化耗时="+(System.nanoTime()-t3));
    }
}
public interface IGsonSerializer {
    <T> byte[] serialize(T obj);
    <T> T deserialize(byte[] data,Class<T> clazz);
}