已添加JSR310依赖仍报错,求java.time.Instant反序列化注解方案
解决Java 8 Instant类型Jackson序列化/反序列化问题
一、使用注解直接处理字段
针对你的场景,完全可以用@JsonDeserialize和@JsonSerialize注解指定Instant对应的处理器,示例如下:
import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.InstantSerializer; public class YourEntity { // 针对输入格式2022-01-21T18:38:55Z,默认的InstantDeserializer即可处理 @JsonDeserialize(using = InstantDeserializer.class) @JsonSerialize(using = InstantSerializer.class) private Instant yourInstantField; // 其他字段、getter和setter }
InstantDeserializer原生支持ISO-8601格式(包括带Z标识的UTC格式),无需额外指定格式规则。
二、排查全局ObjectMapper配置未生效的原因
你之前配置的ObjectMapper Bean如果没生效,常见原因有这些:
- 未给自定义
ObjectMapper添加@Primary注解,导致Spring Boot默认的ObjectMapper被优先使用 - 项目中存在其他配置类定义了
ObjectMapper,覆盖了你的配置 - Spring MVC场景下,需确保自定义
ObjectMapper被绑定到消息转换器,可通过WebMvcConfigurer配置:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(objectMapper()); converters.add(0, converter); } @Bean @Primary // 确保该ObjectMapper被优先注入 ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); // 可选:关闭默认时间戳序列化,让JavaTimeModule按ISO格式处理 objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); return objectMapper; } }
三、额外注意事项
- 确保
jackson-datatype-jsr310依赖版本与jackson核心版本一致,避免版本冲突 - 如果字段上存在
@JsonFormat注解,可能与JavaTimeModule的处理逻辑冲突,可暂时移除测试
内容的提问来源于stack exchange,提问作者mnfsd
相关产品推荐
相关产品推荐

