了解在使用 Jackson 序列化和反序列化 Java 8 日期时间类时修复错误“Java 8 date/time type `java.time.Instant` not supported by default”。
1. 问题
当我们序列化 Java 对象或将 JSON 反序列化为 POJO 时会发生错误,并且 POJO 包含新的 Java 8 日期时间类,如 LocalDate、LocalTime、LocalDateTime 等。
例如,下面的 Employee 类有 LocalDate 类型的字段。
public class Employee {
private Long id;
private String name;
private LocalDate dateOfBirth;
}
当我们序列化这个类的实例时,我们得到以下异常:
Exception in thread "main" java.lang.IllegalArgumentException: Java 8 date/time type `java.time.LocalDate` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.howtodoinjava.core.objectToMap.Employee["dateOfBirth"])
at com.fasterxml.jackson.databind.ObjectMapper ._convert(ObjectMapper.java:4393)
at com.fasterxml.jackson.databind.ObjectMapper .convertValue(ObjectMapper.java:4324)
at com.howtodoinjava.core.objectToMap .ObjectToMapUsingJackson.main(ObjectToMapUsingJackson.java:25)
例外一个例子,
当你访问/actuator/info 节点时,你会发现下面错误页面
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
2. 解决方法
我们必须分两步添加对新 Java 8 类的支持以修复此错误。
首先,添加最新版本的 com.fasterxml.jackson.datatype:jackson-datatype-jsr310 Maven 依赖。
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.4</version>
</dependency>
其次,根据您使用的内容,使用 ObjectMapper 或 JsonMapper 注册模块 JavaTimeModule。
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
//or
JsonMapper jsonMapper = new JsonMapper();
jsonMapper.registerModule(new JavaTimeModule());