Spring Boot下Jackson findAndRegisterModules()无法序列化LocalDateTime求助
问题根因
你自定义的ObjectMapper未被Spring MVC的MappingJackson2HttpMessageConverter消息转换器使用,Spring MVC默认会自行初始化独立的ObjectMapper实例处理接口响应序列化,没有加载你加了@Primary注解的自定义Bean。
可用解决方案
方案1:通过Spring MVC配置注册序列化模块(推荐)
不需要单独定义ObjectMapper Bean,直接配置消息转换器即可,适配所有接口序列化规则:
import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); // 注册Java8时间序列化模块,禁用时间戳格式输出 builder.modules(new JavaTimeModule()) .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); converters.add(new MappingJackson2HttpMessageConverter(builder.build())); } }
禁用
WRITE_DATES_AS_TIMESTAMPS属性后,LocalDateTime会默认序列化为yyyy-MM-dd'T'HH:mm:ss格式的字符串,你也可以通过builder.simpleDateFormat("你需要的格式")自定义输出格式。
方案2:配置文件直接配置(无特殊自定义需求首选)
如果没有其他定制的ObjectMapper规则,不需要写任何Java配置,直接在application.yml中添加如下配置即可,Spring Boot自动装配的ObjectMapper会默认加载jsr310模块:
spring: jackson: serialization: write-dates-as-timestamps: false
方案3:强制消息转换器使用自定义ObjectMapper
如果你必须保留现有的自定义ObjectMapper Bean,手动将其注入到消息转换器中即可:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired private ObjectMapper customObjectMapper; @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // 移除默认的Jackson消息转换器 converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter); // 添加使用自定义ObjectMapper的转换器 converters.add(new MappingJackson2HttpMessageConverter(customObjectMapper)); } }
注意事项
- 不要使用已废弃的
JSR310Module,统一使用JavaTimeModule - 非必要不要手动new ObjectMapper实例,优先使用Spring提供的
Jackson2ObjectMapperBuilder构建,会自动加载classpath下的所有Jackson模块和全局配置 - 检查项目中是否存在其他自定义的消息转换器,避免优先级覆盖导致配置不生效
内容的提问来源于stack exchange,提问作者Muhammad Ahmed Bappi
相关产品推荐
相关产品推荐

