Spring Boot默认使用JackJson作为json转换器,用于生成JSON格式数据,有时候它格式化的日期/日期时间(LocalDate/LocalDateTime)字段并不符合产品的需求,因此需要对它返回的json中的日期和日期时间类型的字段做自定义格式处理。

1、在字段上使用@JsonFormat

@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate birthday;  // 生日
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime; // 系统写入时间

这种方式很灵活,但是由于我使用了MyBatis Generator自动生成数据层代码,不能修改自动生成的Model类,因为随时有可能会删除掉这份MyBatis Generator生成的数据层代码,然后重新再生成一份。

2、在application.properties 统一配置

(1)处理非Java 8的日期类型

非Java 8的日期和日期时间类型,可以在application.properties做如下配置,全局范围控制日期时间的格式化

spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#spring.jackson.serialization.write-dates-as-timestamps=false

(2)处理Java 8的日期类型

上述第一种配置对Java 8类型的日期和日期时间(LocalDate、LocalDateTime)不起效,只能处理遗留的日期格式(如java.util.Date),如果要处理Java 8的日期类型,需要在Spring Boot的SpringMvc配置类中定义Jackson的日期转换格式,如下所示:

/*** @author 李海林 手机:13802780104|微信:lihailin9073|Email:767679879@qq.com* @copyright 个人开发者李海林版权所有,产品详情及技术服务请登录官网查询[http://www.x-core.org.cn]* @create 2019-08-20 18:26*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {private static final String dateFormat = "yyyy-MM-dd";private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";@Beanpublic Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {return builder -> {builder.simpleDateFormat(dateTimeFormat);builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));};}}

这样定义之后,所有被Jackson转换为json格式的日期和日期时间都会统一按照上述代码定义的格式进行处理。

3、自定义JSON转换器来处理日期格式

通过自定义JSON转换器,去掉Spring Boot默认的Jackson-databind,引入FastJson作为新的JSON转换器,然后在自定义FastJson转换器的时候对日期时间进行格式化处理

(1)在pom中引入FastJson并屏蔽more的Jackson-databind

<!-- 在引入web依赖时,屏蔽掉jackson转换器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></exclusion></exclusions></dependency><!-- 引入fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.48</version></dependency>

(2)配置 fastjson 的 HttpMessageConverter

package cn.org.xcore.edusys.config;import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.nio.charset.Charset;/*** FastJson配置类** @author 李海林 手机:13802780104|微信:lihailin9073|Email:767679879@qq.com* @copyright 个人开发者李海林版权所有,产品详情及技术服务请登录官网查询[http://www.x-core.org.cn]* @create 2019-08-29 21:35*/
@Configuration
public class InitFastJsonConfig {@BeanFastJsonHttpMessageConverter fastJsonHttpMessageConverter () {FastJsonHttpMessageConverter converter= new FastJsonHttpMessageConverter();// 创建FastJson转换器的配置FastJsonConfig config = new FastJsonConfig();config.setDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式config.setCharset(Charset.forName("UTF-8")); // 设置编码格式converter.setFastJsonConfig(config);return converter;}}

通过这两步的配置,就启用了FastJson作为json转换器,并且设置了日期的格式为 yyyy-MM-dd HH:mm:ss

订单

Spring Boot 格式化接口返回JSON中的日期/日期时间(LocalDate/LocalDateTime)相关推荐

  1. Spring Boot——统一设置返回Json数据风格(Java驼峰命名法转下划线命名法)解决方案

    基本概念 HttpMessageConverter: org.springframework.http.converter.HttpMessageConverter 是一个策略接口 接口说明如下: S ...

  2. spring boot开发接口api

    spring boot开发接口api ​ 在上一次教了大家怎么去搭建一个自己的后端模板之后,现在和大家分享讨论一下如何开发RestfulApi接口. 首先开发api之前要考虑到后端是需要写api文档的 ...

  3. spring boot处理请求返回值的格式(自定义消息转换器)

    springboot 将对象转化成json对象返回给前端,是通过多个消息转换器配合完成的 但是有些时候,默认的转化格式未必符合我们的要求,这个时候就需要进行自定义消息转换器 只需要在@Configur ...

  4. spring boot 文件下载接口

    文章目录 spring boot 文件下载接口 通过ResponseEntity实现 通过写HttpServletResponse的OutputStream实现 spring boot 文件下载接口 ...

  5. spring boot rest接口自动生成文档(包含swagger)--gradle 下的配置

    之前写过一篇文章:spring boot rest接口自动生成文档(包含swagger),这个使用的是maven作为依赖管理工具,现在,让我们体验一下gradle在spring boot项目中如何配置 ...

  6. 接口返回json对象出现套娃递归问题 | System.Text.Json 版本

    前言 看到一篇文章<Asp-Net-Core开发笔记:接口返回json对象出现套娃递归问题> 原文是使用 NewtonsoftJson 解决的返回json对象出现套娃递归问题: servi ...

  7. spring boot maven项目返回值乱码的解决方法

    spring boot maven项目返回值乱码的解决方法 1.先看乱码效果: spring boot maven项目,返回值乱码,如下图: 控制台打印log乱码,如下图: 有swagger的话,sw ...

  8. Spring MVC 3.0 返回JSON数据的方法

    Spring MVC 3.0 返回JSON数据的方法 1. 直接 PrintWriter 输出 2. 使用 JSP 视图 3. 使用Spring内置的支持 // Spring MVC 配置 <b ...

  9. java调用远程 接口_java通过url调用远程接口返回json数据

    java通过url调用远程接口返回json数据,有用户名和密码验证, 转自 https://blog.csdn.net/wanglong1990421/article/details/78815856 ...

最新文章

  1. 怎么提高面试成功率?
  2. 中文TTS文字转语音合成模块合成成品带喇叭 替代SYN6288和XFS5152
  3. 【Paper】2022_基于无人驾驶地面车辆的多Agent系统仿真平台的设计及编队控制协议的研究
  4. pgsql 筛选中文字符正则_「每日一练」巧用Python对字符串进行筛选
  5. jquery实现上线翻滚效果公告
  6. 图解Kafka,一看就明白!
  7. php有哪些debug方式,Console有哪些Debug方法
  8. 我喜欢这个地方,是因为和你一起走过
  9. 【工具】Get Data-获取论文图片中数据的工具
  10. 乌龟Git Permission denied
  11. 图论 —— 最短路 —— Johnson 算法
  12. 基于YOLOv5的汽车座椅缺陷检测
  13. 【第14章】恶意代码防范技术原理@信息安全工程师 软考笔记
  14. ibm服务器开机显示如何设置,IBM服务器开机进入WEBBIOS界面配置RAID
  15. vue 实现评论回复功能
  16. 哈工大车万翔:自然语言处理范式正在变迁
  17. pin limiting the speed
  18. 在安卓手机上搭建一台微型服务器
  19. Android 系统语言切换监听和设置
  20. 怎么确定电视吊架安装位置,电视支架安装讲解

热门文章

  1. 微信小程序自定义复选框
  2. python讲师金角大王_python 金角大王博客园学习地址
  3. 上证50ETF期权的五大优势:
  4. Efficient Text-based Reinforcement Learning by Jointly LeveragingState and Commonsense Graph Repres
  5. WinXP 性能优化
  6. 机器学习笔记 - 如何对两个分类变量使用卡方检验?
  7. 关于squeeze unsqueeze 以及expand的学习
  8. ROS:参数服务器通信
  9. Nebulogy携手福耀集团,助力制造业智能化转型
  10. MySQL SQL 优化参数 引发的悲剧