Java序列化高級

在上一節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());
    }
}
發佈了54 篇原創文章 · 獲贊 15 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章