前言:在开发国际化项目的过程中,使用 Jackson 序列化时间类型的数据导致的相关问题。
1、现象
在开发国际化项目中发现,数据库取出的时间和对象拿到的时间都是一致的,但是通过 postman 调用接口展示的时候,时间和数据库的时间相差8小时。
2、原因
SpringBoot 默认使用 Jackson 为序列化工具,Jackson 在没有指定序列化和反序列化形式的情况下,会采用默认的序列化方式。
其中 date 类型的数据,默认的序列化格式如下:
1 |
|
其中时间的默认时区为UTC+0,在传输的过程中,会以字符串的形式按照上面的格式进行序列化。而国内的时区是 UTC+8,所以最终时间会相差 8小时。
各个符号解释:
符号 | 解释 |
---|---|
YYYY | is the decimal digits of the year 0000 to 9999 in the Gregorian calendar. |
- | “-“ (hyphen) appears literally twice in the string. |
MM | is the month of the year from 01 (January) to 12 (December). |
DD | is the day of the month from 01 to 31. |
T | “T” appears literally in the string, to indicate the beginning of the time element. |
HH | is the number of complete hours that have passed since midnight as two decimal digits from 00 to 24. |
: | “:” (colon) appears literally twice in the string. |
mm | is the number of complete minutes since the start of the hour as two decimal digits from 00 to 59. |
ss | is the number of complete seconds since the start of the minute as two decimal digits from 00 to 59. |
. | “.” (dot) appears literally in the string. |
sss | is the number of complete milliseconds since the start of the second as three decimal digits. |
Z | is the time zone offset specified as “Z” (for UTC) or either “+” or “-“ followed by a time expression HH:mm |
3、解决
①前端拿到这样的数据的时候,需要做如下处理:
1 |
|
格式化前后的区别:
②如果使用 Fegin Client
需要确认服务端的时间格式,如果没有指定格式,则使用默认格式。
具体使用:在对应字段加上 @JsonFormat 注解即可,如下所示:
1 |
|
③SpringBoot 全局配置 JsonFormat date的序列化方式
在 application.yml 文件加入如下配置:
1 |
|
4、其他问题
①支持 Java 8
1 |
|
在添加 JSR-310 模块后, 让 jackson 能够识别出 Java 8 的日期 & 时间类型(pom.xml)
参考文章
https://blog.csdn.net/aerchi/article/details/78717232
https://xiaoym.gitee.io/2021/03/26/spring-boot-code-action-jackson/
- 本文作者: th3ee9ine
- 本文链接: https://www.blog.ajie39.top/2021/12/03/Jackson序列化时间导致的相关问题/
- 版权声明: 本博客所有文章除特别声明外,均采用 LICENSE 下的许可协议。转载请注明出处!