Java 对象转 JSON

文档介绍如何使用 Jackson 库将 Java 对象转换为 JSON 字符串包含复杂类型。Jackson 用于处理 JSON 数据格式的序列化和反序列化。

1 引入 Jackson 依赖

在项目中引入 Jackson 的依赖,可以通过 Maven、Gradle 或直接下载 JAR 文件实现。以下是 Maven 引入示例:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

2 创建 Java 对象

创建一个 Java 对象,该对象将被转换为 JSON 字符串

public class Person {
    private String name;
    //.......其他

}

3 创建 ObjectMapper 对象

创建 ObjectMapper 对象, Jackson 中负责序列化和反序列化的核心类

ObjectMapper objectMapper = new ObjectMapper();

4 序列化 Java 对象

使用 ObjectMapperwriteValueAsString 方法将 Java 对象转换为 JSON 字符串

//例如
public class ObjectToJsonExample {
    public static void main(String[] args) throws Exception {
        Person person = new Person();
        person.setName("****");
        //.....其他

        String jsonString = objectMapper.writeValueAsString(person);
        System.out.println(jsonString);
    }
}

5 使用注解定制字段

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonFormat;

public class CustomSerializationObject {
    @JsonProperty("full_name")
    private String name;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birthDate;

    // .....其他
}

6 序列化包含注解的对象

public class CustomSerializationExample {
    public static void main(String[] args) throws Exception {
        CustomSerializationObject customObject = new CustomSerializationObject("*****", new Date());

        String jsonString = objectMapper.writeValueAsString(customObject);
        System.out.println(jsonString);
    }
}

7 定义包含复杂类型和集合的类

public class ListObject {
    private List<Person> people;
  
}

8 序列化包含复杂类型的对象

public class ListSerializationExample {
    public static void main(String[] args) throws Exception {
        List<Person> peopleList = new ArrayList<>();
        peopleList.add(new Person("Alice", 25));
        //.....其他

        ListObject listObject = new ListObject(peopleList);

        String jsonString = objectMapper.writeValueAsString(listObject);
        System.out.println(jsonString);
    }
}


Java 对象转 JSON
http://localhost:8090//archives/java-dui-xiang-zhuan-json
作者
chenll
发布于
2024年08月18日
许可协议