目录
一. 报错信息
最近新开了一个测试项目,使用了Java8的LocalDateTime替换了之前使用的Date类。接口返回结果时,抛出了序列化异常:
java.lang.reflect.UndeclaredThrowableException: null
…………
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default:
add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain:
cn.xx.dao.common.Back["data"]->cn.xx.dao.data.vo.BmVo["spe"]->
cn.xx.dao.entity.Spe["createTime"])
二. 版本信息
spring boot:2.5.1
jackson-databind:2.12.3
……
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
……
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
三. 解决方法
1. 使用@JsonSerialize + @JsonDeserialize注解
- pom加上这两个注解的依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.12.3</version>
</dependency>
- 在使用LocalDateTime的属性上添加这两个序列化反序列化注解:
@JsonSerialize(using = Loc

文章介绍了在使用SpringBoot2.5.1时遇到的LocalDateTime序列化异常,由于Java8的时间类型不被默认支持,提出了三种解决方案:1)使用@JsonSerialize和@JsonDeserialize注解;2)回退SpringBoot版本到2.4.x;3)回退jackson-databind版本到2.11.x。此外,还尝试了注册JavaTimeModule和自定义Jackson2ObjectMapperBuilder,但未解决问题。
最低0.47元/天 解锁文章
184





