spring.mvc.converters.preferred-json-mapper: jackson
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return b ->
b.simpleDateFormat("yyyy-MM-dd HH:mm:ss")
// long类型转string, 前端处理Long类型,数值过大会丢失精度
.serializerByType(Long.class, ToStringSerializer.instance)
.serializerByType(Long.TYPE, ToStringSerializer.instance)
.serializationInclusion(JsonInclude.Include.NON_NULL)
//指定反序列化类型,也可以使用@JsonFormat(pattern = "yyyy-MM-dd")替代。主要是mvc接收日期时使用
.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
// 日期序列化,主要返回数据时使用
.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}
使用我们自定义的 Jackson2ObjectMapperBuilderCustomizer
生成Jackson2ObjectMapperBuilder
根据Jackson2ObjectMapperBuilder生成ObjectMapper
springboot mvc默认使用的Jackson,
跟据ObjectMapper生成MappingJackson2HttpMessageConverter
MappingJackson2HttpMessageConverter 生成HttpMessageConverters
WebMvcAutoConfigurationAdapter里面有
把生成的HttpMessageConverters自动配置到mvc