You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vert.x中Jackson处理Java 8 LocalDateTime序列化与反序列化异常

问题原因

你遇到的问题是Jackson默认没有内置java.time包下JSR310时间类型的序列化/反序列化支持,所以会把LocalDateTime拆解为嵌套属性对象输出,同时反序列化时因为LocalDateTime没有公开无参构造方法,就会抛出实例化失败的错误。

解决步骤

1. 引入JSR310支持依赖

首先添加Jackson对Java8时间类型的支持模块,注意版本要和你项目中现有jackson-databind版本保持一致(你当前用的是2.11.4)
Maven依赖配置:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.11.4</version>
</dependency>

Gradle依赖配置:

implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.11.4'

2. 选择配置方式

两种配置方式二选一即可:

方式一:全局配置(推荐,无需修改每个实体类)

因为你使用Vert.x框架,只需要在初始化Vertx实例时,注入自定义配置的ObjectMapper即可:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;

// 自定义ObjectMapper配置
ObjectMapper objectMapper = new ObjectMapper()
        // 注册JSR310 Java8时间模块
        .registerModule(new JavaTimeModule())
        // 关闭将时间序列化为时间戳/属性对象的特性,开启后输出ISO格式字符串
        .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

// 将自定义ObjectMapper注册到Vertx实例
Vertx vertx = Vertx.vertx(new VertxOptions()
        .setObjectMapper(objectMapper));

方式二:字段单独注解配置(灵活,不需要改全局配置)

直接在RefreshToken实体类的时间字段上添加序列化注解,同时补充必要的无参构造、getter/setter:

import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;

public class RefreshToken {
    private Integer id;
    private Integer userID;
    private Integer deviceID;
    private String refreshToken;

    // 指定序列化/反序列化的时间格式
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
    private LocalDateTime issuedAt;
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
    private LocalDateTime expiresAt;

    // 必须添加无参构造方法,供Jackson反序列化实例化对象使用
    public RefreshToken() {}

    // 省略剩余字段的getter、setter方法,所有字段必须要有对应的getter和setter
}

验证效果

配置完成后重新运行,序列化输出的JSON中时间字段会变为你期望的2021-10-26T12:36:10格式,mapTo方法反序列化也不会再报错。

内容的提问来源于stack exchange,提问作者ZAJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:45:08