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

合并Jackson自定义反序列化注解时出现LocalDateTime解析报错求解决

问题解决步骤

核心原因

合并注解后Jackson未识别内部的@JsonDeserialize配置,转而使用默认逻辑处理LocalDateTime,因此触发了未注册JavaTimeModule的报错(实际模块已存在,只是自定义注解未被正确解析)。

解决操作

1. 给自定义组合注解添加@JacksonAnnotationsInside

这个注解是Jackson识别组合注解内部Jackson注解的关键,必须添加到你的@TDeserializer上:

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside // 告诉Jackson解析该注解内部的Jackson相关注解
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@TDateFormat // 你的自定义日期格式注解
public @interface TDeserializer {
}

2. 确保自定义反序列化器能读取@TDateFormat的配置

在LocalDateTimeDeserializer中,需要从字段上获取@TDateFormat的格式值,避免硬编码格式:

public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {

    public LocalDateTimeDeserializer() {
        super(LocalDateTime.class);
    }

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateStr = p.getText();
        // 获取字段上的@TDateFormat注解
        TDateFormat dateFormatAnn = p.getParsingContext().getCurrentBeanProperty().getAnnotation(TDateFormat.class);
        if (dateFormatAnn == null) {
            throw new IllegalArgumentException("字段未配置@TDateFormat注解");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormatAnn.value());
        return LocalDateTime.parse(dateStr, formatter);
    }
}

3. 确认ObjectMapper已注册JavaTimeModule(可选但稳妥)

虽然单独使用时正常,但合并注解后可手动确保模块注册,避免环境差异问题:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:40:27