LocalDateTime的json格式化问题

川长思鸟来 2024-03-22 21:03 136阅读 0赞

LocalDateTime 的 json 格式化存在问题如图所示:

1fbf73f82cb14cdf8a364900298eddbf.png

解决方式一:添加json格式化配置文件:

  1. package com.buba.yka.base.config;
  2. import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9. /**
  10. * 针对LocalDateTime时间类型的json格式化转换问题,方案全局生效
  11. * 这个时间类型的字段返回给前端是:2023-07-25T14:24:28
  12. * 对日期格式要做特殊的处理:yyyy-MM-dd HH:mm:ss
  13. * 格式化后:2023-07-25 14:24:28
  14. */
  15. @Configuration
  16. public class LocalDateTimeSerializerConfig {
  17. @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
  18. private String pattern;
  19. //序列化器,根据pattern yyyy-MM-dd HH:mm:ss格式,对LocalDateTime序列化
  20. public LocalDateTimeSerializer localDateTimeDeserializer() {
  21. return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
  22. }
  23. //调用了LocalDateTimeSerializer序列化器
  24. @Bean
  25. public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
  26. return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
  27. }
  28. }

195607d2fe08447da5c897f0d82ad1a7.png

解决方式二:@JsonFormat 自定义注解

  1. 上面的方案全局生效,当全局的格式化方式无法满足我们需求时,我们对日期格式要做特殊的处理:在类的属性上添加注解
  2. @JsonFormat(pattern = "yyyy-MM-dd")
  3. @ApiModelProperty(value = "创建时间")
  4. private LocalDateTime createTime;

32b23f1a41bc465285eaf7b1803cbcd0.png

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读