Springboot2.x配置ObjectMapper日期格式化不生效的问题解决
问题起因:与前端对接接口发现日期时间输出格式是数组,而代码中又有ObjectMapper格式化日期配置
环境:springboot2.x+jdk1.8
相关代码配置类
@Configuration
public class JacksonConfig {
@Primary
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//省略LocalDate、LocalTime的配置
objectMapper.registerModule(javaTimeModule);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}
@EnableWebMvc
@Component
public class MyWebMvcConfig implements WebMvcConfigurer {
//省略一些常用配置
}问题排查思路:
- 使用自动注入ObjectMapper,查看bean配置是否生效,bebug结果显示配置是注入到bean中

- 通过调用栈debug到AbstractJackson2HttpMessageConverter类,发现与注入的ObjectMapper的配置不一致
private ObjectMapper selectObjectMapper(Class<?> targetType, @Nullable MediaType targetMediaType)

- 搜索发现代码注入@EnableWebMvc。将注解注释后重新bebug发现配置生效了。
解决方案:
方案一:直接删除@EnableWebMvc注解重启生效
方案二:保持原代码不动,在实现WebMvcConfigurer的类中重写extendMessageConverters方法
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
((MappingJackson2HttpMessageConverter) converter).setObjectMapper(objectMapper);
break;
}
}
}方案三:在LocalDateTime、LocalDate、LocalTime等字段使用@JsonFormat,如果接受参数类型也是日期时间类型,建议也加上@DateTimeFormat
因为是接手别人的代码,线上已经运行,没有办法只有选择方案二、方案三
到此这篇关于Springboot2.x配置ObjectMapper日期格式化不生效的文章就介绍到这了,更多相关Springboot2.x配置ObjectMapper日期格式化不生效内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
- Springboot2.x配置ObjectMapper日期格式化不生效的问题解决
- SpringBoot中Jackson ObjectMapper应用及说明
- Springboot通过ObjectMapper配置json序列化详解
- 解决springboot项目启动失败Could not initialize class com.fasterxml.jackson.databind.ObjectMapper问题
- springboot~ObjectMapper~dto到entity的自动赋值
- Springboot配置返回日期格式化五种方法详解
- springboot全局日期格式化的两种方式
- SpringBoot基于HttpMessageConverter实现全局日期格式化
- SpringBoot2.0整合jackson配置日期格式化和反序列化的实现
相关文章
5分钟快速搭建SpringBoot3 + MyBatis-Plus工程/项目的实现示例
本文主要介绍了使用IntelliJ IDEA创建Spring Boot工程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2025-01-01
SpringBoot中GlobalExceptionHandler异常处理机制详细说明
Spring Boot的GlobalExceptionHandler是一个全局异常处理器,用于捕获和处理应用程序中发生的所有异常,这篇文章主要给大家介绍了关于Java中GlobalExceptionHandler异常处理机制的相关资料,需要的朋友可以参考下2024-03-03
Java并发编程之ConcurrentLinkedQueue队列详情
这篇文章主要介绍了Java并发编程之ConcurrentLinkedQueue队列详情,ConcurrentLinkedQueue 内部的队列使用单向链表方式实现,下文更多相关内容叙述需要的小伙伴可以参考一下2022-04-04


最新评论