jackson全局配置解析localDateTime

  • 相信很多前端对接后段时间类型转换的问题,时间格式不一致的问题,通过jackson也可以做到全局的配置,不在使用注解单个判断时间类型
引入的maven  

 cn.hutool
 hutool-all
 5.5.1
///配置自定义model
public class LocalJavaTimeModule extends SimpleModule {

public CustomJavaTimeModule() {
super(PackageVersion.VERSION);
this.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(
DatePattern.NORM_DATETIME_PATTERN)));
this.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
this.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
this.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
this.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
this.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));

}
@Configuration
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfig {

@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> {
/**
* 配置Date的格式化
*/
builder.locale(Locale.CHINA);
builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
/**
* 配置java8 时间配置
*/
builder.modules(new LocalJavaTimeModule());
};
}
}

这样就可以了,当然多模块可以做成一个插件starter之类的

你可能感兴趣的:(java,springboot,jackson,datetime)