Springboot 2.x LocalDateTime 序列化
程序员文章站
2022-05-01 15:33:37
...
springboot2.x 对java8 LocalDateTime序列化需要手动设置。
首先引入依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
然后在application.yaml配置文件添加如下配置:
spring:
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
把序列化时间格式统一设置成yyyy-MM-dd HH:mm:ss,接下来增加jackson的一些配置:
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(Constants.DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(Constants.DEFAULT_DATE_FORMAT)));
javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(Constants.DEFAULT_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(Constants.DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(Constants.DEFAULT_DATE_FORMAT)));
javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(Constants.DEFAULT_TIME_FORMAT)));
objectMapper.registerModule(javaTimeModule).registerModule(new ParameterNamesModule());
return objectMapper;
}
}
public class Constants {
/**时间格式**/
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**日期格式**/
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/**时钟格式**/
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public Constants() {
}
}
这样就配置完成了!
我配置了Swagger2,用Swagger2查看效果如下:
推荐阅读
-
SpringBoot中对LocalDateTime进行格式化
-
springboot~mybatis里localdatetime序列化问题
-
SpringBoot 2.x 开发案例之 Shiro 整合 Redis
-
SpringBoot 2.x (1):手动创建项目与自动创建项目
-
springboot 项目中获取默认注入的序列化对象 ObjectMapper
-
springboot LocalDateTime 反序列化
-
SpringBoot整合SpringMVC之自定义JSON序列化器和反序列化器
-
SpringBoot2.3整合redis缓存自定义序列化的实现
-
SpringBoot 2.x 整合Mybatis三:tk.mybatis
-
SpringBoot 2.x (3):文件上传