0


SpringBoot全局处理LocalDateTime返回格式和Long类型序列化

在spring Boot项目开发中,我们经常遇到后端是LocalDateTime类型或LocalDate类型,然后返回给前端格式不对的问题,以及后端是Long类型,但返回给前端Long的话出现精度丢失的问题,解决的方法可以给返回VO类中的字段一个一个加上注解,但是这样效率太低了,于是找到了一种全局处理的方法。

1.参考

SpringBoot–LocalDateTime–全局格式转换/前端入参/响应给前端_51CTO博客_springboot localdatetime

2.对Date类型做处理

先讲下,对于java.util.Date类型的统一处理:

在application.properties或application.yml文件中,你可以添加以下配置来设置日期格式:

  1. #json格式化全局配置
  2. spring.jackson.time-zone=GMT+8
  3. spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
  4. spring.jackson.serialization.write-dates-as-timestamps=false
  1. spring:jackson:date-format: yyyy-MM-dd HH:mm:ss
  2. time-zone: GMT+8
  3. serialization:write-dates-as-timestamps:false

3.对LocalDateTime和LocalDate做处理

但是,如果是 LocalDateTime类型或LocalDate类型 上面的配置并不会生效

参考SpringBoot–LocalDateTime–全局格式转换/前端入参/响应给前端_51CTO博客_springboot localdatetime

由于我项目中用到了

  1. WebMvcConfig implements WebMvcConfigurer

所以用普通的

  1. ObjectMapper+自定义序列化

或者

  1. ackson2ObjectMapperBuilderCustomizer

会失效

最终采用 直接配置在

  1. WebMvcConfig

类中实现

代码如下:

  1. @Configuration@EnableWebMvcpublicclassWebMvcConfigimplementsWebMvcConfigurer{/**
  2. * 格式化 LocalDateTime 和 LocalDate
  3. * @param converters
  4. */@OverridepublicvoidconfigureMessageConverters(List<HttpMessageConverter<?>> converters){// Create a Jackson2ObjectMapperBuilder to customize ObjectMapperJackson2ObjectMapperBuilder builder =newJackson2ObjectMapperBuilder();
  5. builder.modules(newJavaTimeModule());// Customize LocalDateTime serialization
  6. builder.serializerByType(LocalDateTime.class,newLocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  7. builder.serializerByType(LocalDate.class,newLocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));// Configure converters with customized ObjectMapper
  8. converters.add(newMappingJackson2HttpMessageConverter(builder.build()));}/**
  9. * 全局给Long类型加上@JsonSerialize(using = ToStringSerializer.class)
  10. * @param converters
  11. */@OverridepublicvoidextendMessageConverters(List<HttpMessageConverter<?>> converters){for(HttpMessageConverter<?> converter : converters){if(converter instanceofMappingJackson2HttpMessageConverter){MappingJackson2HttpMessageConverter jsonConverter =(MappingJackson2HttpMessageConverter) converter;ObjectMapper objectMapper = jsonConverter.getObjectMapper();SimpleModule simpleModule =newSimpleModule();
  12. simpleModule.addSerializer(Long.class,newToStringSerializer());
  13. objectMapper.registerModule(simpleModule);}}}}

这里注意当get请求的接口,使用了@ApiParam注解时,会失效,使用@RequestParam则不会,暂时没找到原因和解决方案

4.对Long类型做序列化处理

同理,如上面代码所示

5.最终效果

VO类

  1. packagecom.znak.spmp.emergency.vo;importcom.fasterxml.jackson.annotation.JsonFormat;importcom.fasterxml.jackson.databind.annotation.JsonSerialize;importcom.fasterxml.jackson.databind.ser.std.ToStringSerializer;importcom.znak.spmp.file.dto.FileDTO;importio.swagger.annotations.ApiModelProperty;importlombok.AllArgsConstructor;importlombok.Builder;importlombok.Data;importlombok.NoArgsConstructor;importjava.time.LocalDate;importjava.time.LocalDateTime;importjava.util.List;/**
  2. * @author xu yue
  3. * @date 2024/7/12
  4. * @Description
  5. */@Data@AllArgsConstructor@NoArgsConstructor@BuilderpublicclassEmergencyPlanVO{/**
  6. * id
  7. */@ApiModelProperty("id")privateLong id;/**
  8. * 二级单位简称id
  9. */@ApiModelProperty("二级单位简称id")privateLong orgShortNameId;/**
  10. * 二级单位简称
  11. */@ApiModelProperty("二级单位简称")privateString orgShortName;/**
  12. * 单位id
  13. */@ApiModelProperty("单位id")privateLong organizeId;/**
  14. * 单位名称
  15. */@ApiModelProperty("单位名称")privateString organizeName;/**
  16. * 应对事故类型
  17. */@ApiModelProperty("应对事故类型")privateList<String> riskAccidentsIds;/**
  18. * 预案备案标号
  19. */@ApiModelProperty("预案备案标号")privateString registrationLabel;/**
  20. * 所属行业
  21. */@ApiModelProperty("所属行业")privateString industry;/**
  22. * 预案名称
  23. */@ApiModelProperty("预案名称")privateString name;/**
  24. * 发布日期
  25. */@ApiModelProperty("发布日期")privateLocalDate publishDate;/**
  26. * 预案附件
  27. */@ApiModelProperty("预案附件")privateList<FileDTO> files;/**
  28. * 是否备案(0否1是)
  29. */@ApiModelProperty("是否备案(0否1是)")privateInteger register;/**
  30. * 备案形式(0内部(向集团内上级单位备案);1外部(向政府职能部门备案))
  31. */@ApiModelProperty("备案形式(0内部(向集团内上级单位备案);1外部(向政府职能部门备案))")privateInteger registerType;/**
  32. * 备案内容
  33. */@ApiModelProperty("备案内容")privateString registerContent;/**
  34. * 备案附件
  35. */@ApiModelProperty("备案附件")privateList<FileDTO> registerFiles;/**
  36. * 备案部门
  37. */@ApiModelProperty("备案部门")privateString registerDepartment;/**
  38. * 外部备案部门
  39. */@ApiModelProperty("外部备案部门")privateString outsideRegisterDepartment;/**
  40. * 备案时间
  41. */@ApiModelProperty("备案时间")privateLocalDate registerDate;/**
  42. * 场所id
  43. */@ApiModelProperty("场所id")privateLong locationId;/**
  44. * 场所
  45. */@ApiModelProperty("场所")privateString location;/**
  46. * 所属街道
  47. */@ApiModelProperty("所属街道")privateString subStreet;/**
  48. * 应急预案类别(处置方案类别)
  49. */@ApiModelProperty("应急预案类别(处置方案类别)")privateLong emergencyPlanTypeId;/**
  50. * 应急预案类别名(处置方案类别名)
  51. */@ApiModelProperty("应急预案类别名(处置方案类别名)")privateString emergencyPlanType;/**
  52. * 创建人真实姓名
  53. */@ApiModelProperty("创建人真实姓名")privateString createBy;/**
  54. * 创建时间
  55. */@ApiModelProperty("创建时间")privateLocalDateTime createTime;/**
  56. * 更新时间
  57. */@ApiModelProperty("更新时间")privateLocalDateTime updateTime;}

返回结果

在这里插入图片描述

标签: java 笔记 spring boot

本文转载自: https://blog.csdn.net/m0_52620144/article/details/140543126
版权归原作者 NEIL_XU_ 所有, 如有侵权,请联系我们删除。

“SpringBoot全局处理LocalDateTime返回格式和Long类型序列化”的评论:

还没有评论