Java序列化高级

来源:互联网 发布:期货自动交易编程 编辑:程序博客网 时间:2024/06/05 20:50

在上一节Java序列化基础中,介绍了JDK自带的序列化方式。本节,将介绍一些常见的序列化框架。

1、XML和JSON

XML和JSON是两种常见的数据传输格式,由于Json格式使用场景更广,序列化体积小的优点,以下将重点介绍Json序列化以及反序列化。

添加Maven依赖,使用FastJson作为序列化工具,其他的还有Jackson、Gson等Json序列化工具。

<dependency>     <groupId>com.alibaba</groupId>     <artifactId>fastjson</artifactId>     <version>1.2.24</version></dependency>

依然采用上节中的Person.class作为序列化对象:

public class TestJsonSerializable {    public static void main(String[] args) {        Person person = new Person(1001, 18, true, "Jack", "BeiJing");        // json 序列化        String jsonStr = JSON.toJSONString(person);        System.out.println(jsonStr);        // json 反序列化        Person p =  JSON.parseObject(jsonStr, Person.class);        System.out.println(p.toString());    }} // output// {"addr":"BeiJing","age":18,"id":1001,"name":"Jack","sex":true}// Person{id=1001, age=18, sex=true, name='Jack', addr='BeiJing'}

2、Kryo序列化

简单上手,下面的例子是将对象序列化到文件中,然后在从文件中反序列化到内存中。

public class TestKryoSerializable {    public static void main(String[] args) throws Exception {        Person person = new Person(1001, 18, true, "Jack", "BeiJing");        // Kryo 序列化        Kryo kryo = new Kryo();        Output output = new Output(new FileOutputStream("Person.dat"));        kryo.writeObject(output, person);        output.close();        // Kryo 反序列化        Input input = new Input(new FileInputStream("Person.dat"));        Person p = kryo.readObject(input, Person.class);        input.close();        System.out.println(p.toString());    }}
原创粉丝点击