Java jackson序列化与反序列化的简单实战

350 阅读2分钟

在日常的运用开发中,序列化是我们不可回避会遇到的开发问题,在 python 中我们可以用 json 库解决,在 golang 中,同样存在标准库的 json 库供我们日常开发使用,在 Java 中,如果仅用 ObjectInputStream/ObjectOutputStream 显然是不够的。

今天此文分享的,是基于 jackson 这个使用者甚多的第三方库来实现我们的数据序列化需求。

提到序列化,顾名思义就是将我们内存中的一些对象,如字符串、map、list、object等数据转为json串或者持久化到文件中或者用于网络传输。

先介绍下常用接口:

序列化

  • String writeValueAsString(Object value),传入对象,返回字符串
  • writeValue(File resultFile, Object value),将对象数据序列化到文件
  • writerWithDefaultPrettyPrinter().writeValue(File resultFile, Object value),将对象数据序列化到文件中,通过indent显示

反序列化

  • T readValue(String content, Calss<T>),读取字符串反序列化到类实例
  • T readValue(File src, Class<T>),从json文件反序列化到类实例

下面是个简单例子:

Person类

package org.example;

public class Person {
   private String name;
   private int age;

   public Person() {
   }

   public Person(String name, int age) {
       this.name = name;
       this.age = age;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public int getAge() {
       return age;
   }

   public void setAge(int age) {
       this.age = age;
   }
}

Person类就是 Java Bean。

序列化与反序列化

package org.example;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
    
public class Main {
    public static void main(String[] args) {
        // serialize to string in memory
        serializable();
        deserializable();

        // serialize to file
        serializableToFile();
        deserializableFromFile();

        // serialize complex object to file, and with indent
        serializableToFileWithComplexObject();
        deserializableFromFileWithComplexObject();

    }

    // demo: serializable and deserializable with json string and object(in memory)
    public static void serializable() {
        ObjectMapper om = new ObjectMapper();
        Person person = new Person("Alice", 30);

        try {
            String jsonSTring = om.writeValueAsString(person);
            System.out.println(jsonSTring);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public static void deserializable() {
        ObjectMapper om = new ObjectMapper();
        String jsonString = "{"name":"Alice","age":30}";

        try {
            Person person = om.readValue(jsonString, Person.class);
            System.out.printf("Name: %s, Age: %d\n", person.getName(), person.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // demo: serialize to file
    public static void serializableToFile() {
        String filePath = "D:\software\intelli D\myDemo\src\learnjava\project\jacksonABC\src\main\resources\person.json";

        ObjectMapper om = new ObjectMapper();
        Person person = new Person("Alice", 30);
        try {
            om.writeValue(new File(filePath), person);
            System.out.println("Object serialize to file ok!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deserializableFromFile() {
        String filePath = "D:\software\intelli D\myDemo\src\learnjava\project\jacksonABC\src\main\resources\person.json";

        ObjectMapper om = new ObjectMapper();

        try {
            Person person = om.readValue(new File(filePath), Person.class);
            System.out.printf("Deserialize from file, Name: %s, Age: %d\n", person.getName(), person.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // demo: complex object
    public static void serializableToFileWithComplexObject() {
        String filePath = "D:\software\intelli D\myDemo\src\learnjava\project\jacksonABC\src\main\resources\detailedPerson.json";

        ObjectMapper om = new ObjectMapper();
        DetailPersonInfo person = DetailPersonInfo.getInstance();
        try {
            om.writerWithDefaultPrettyPrinter().writeValue(new File(filePath), person); // output to file
            String jsonString = om.writerWithDefaultPrettyPrinter().writeValueAsString(person); // output to console
            System.out.println("Complex object serialize to file ok!");
            System.out.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deserializableFromFileWithComplexObject() {
        String filePath = "D:\software\intelli D\myDemo\src\learnjava\project\jacksonABC\src\main\resources\detailedPerson.json";

        ObjectMapper om = new ObjectMapper();

        try {
            DetailPersonInfo person = om.readValue(new File(filePath), DetailPersonInfo.class);
            System.out.println(person.getName() + " " + person.getId() + "" + person.getHobbies().toString() + "" + person.getSalary().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
}    

对应的的maven工程xml配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>jacksonABC</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- Jackson core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.13.0</version>
        </dependency>
        <!-- Jackson databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.0</version>
        </dependency>
        <!-- Jackson annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.13.0</version>
        </dependency>
     </dependencies>

</project>

参考: