SpringBoot利用jackson格式化時間的三種方法
前言
在實際開發(fā)中我們經(jīng)常會與時間打交道,那這就會涉及到一個時間格式轉(zhuǎn)換的問題。接下來會介紹幾種在SpirngBoot中如何對時間格式進行轉(zhuǎn)換。
準(zhǔn)備工作
創(chuàng)建項目,添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
創(chuàng)建實體類UserDTO
添加屬性,get、set方法省略。
private String id; private String username; private Date createTime;
創(chuàng)建UserController
編寫控制層代碼
@RestController
public class UserController {
@GetMapping("/getUser")
public List<UserDTO> getUser() {
List<UserDTO> userList = new ArrayList<UserDTO>();
for (int i=1; i<=3; i++) {
UserDTO user = new UserDTO();
user.setCreateTime(new Date());
user.setUsername("gongj" + i);
user.setId("j" + i);
userList.add(user);
}
return userList;
}
}
調(diào)用接口:http://localhost:8080/getUser

該結(jié)果很顯然不是我們所需要的,所以我們需要進行時間格式化一下。而且還有時區(qū)問題,我當(dāng)前時間是晚上 22:44。
第一種 使用注解
在需要轉(zhuǎn)換的字段上增加 @JsonFormat注解,該注解是 jackson的,web 包集成了。
import com.fasterxml.jackson.annotation.JsonFormat; private String id; private String username; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date createTime;
pattern:需要轉(zhuǎn)換的時間日期的格式
timezone:時間設(shè)置為東八區(qū),避免時間在轉(zhuǎn)換中有誤差
調(diào)用接口:http://localhost:8080/getUser

完成,但是這種也有不好的地方,如果我有一百個實體中都有 Date類型,那就要在一百個實體加入注解。顯得有點麻煩。
第二種 修改默認(rèn)配置
所有的json生成都離不開相關(guān)的HttpMessageConverters
SpringBoot 默認(rèn)使用 jackson,并對其默認(rèn)做了配置。所以我們來修改一下。
全局搜索 JacksonHttpMessageConvertersConfiguration。idea快捷鍵:Ctrl + shift + r

該類中有個方法mappingJackson2HttpMessageConverter 就是用來處理json的。
@Bean
@ConditionalOnMissingBean(
value = {MappingJackson2HttpMessageConverter.class},
ignoredType = {"org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter"}
)
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
return new MappingJackson2HttpMessageConverter(objectMapper);
}
注意該方法上有兩個注解,@Bean 注解就不在介紹了。介紹一下 ConditionalOnMissingBean注解。
@ConditionalOnMissingBean :當(dāng)給定的在bean不存在時,則實例化當(dāng)前 Bean。
打個比喻:你入職報到,你公司看你帶了電腦,就讓你使用你自己的電腦,如果你沒帶電腦,就讓你使用公司的電腦。SpringBoot 也是這樣子做的,你不提供,就使用默認(rèn)的。
新建MyConfig
import java.text.SimpleDateFormat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class MyConfig {
@Bean
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverterConfiguration() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper om = new ObjectMapper();
//全局修改josn時間格式
om.setDateFormat(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
converter.setObjectMapper(om);
return converter;
}
}
提供了一個 MappingJackson2HttpMessageConverter的 Bean ,所以Springboot就會使用我們所提供的。
將User實體的注解注釋

調(diào)用接口:http://localhost:8080/getUser

OK,這種方式也是可以的。
提供ObjectMapper
也可以提供一個 ObjectMapper,將上述提供的 MappingJackson2HttpMessageConverter進行注釋掉。
import java.text.SimpleDateFormat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
@Bean
ObjectMapper objectMapper() {
ObjectMapper om = new ObjectMapper();
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
return om;
}
調(diào)用接口:http://localhost:8080/getUser

注意:上述兩種方法都是全局修改的哦!
第三種 配置文件修改
在 application.yml或者properties中修改默認(rèn)配置
yml
spring:
jackson:
date-format: yyyy/MM/dd
timezone: GMT+8
properties
spring.jackson.date-format=yyyy-MM-dd HH:mm spring.jackson.time-zone=GMT+8
如果第二種方式和第三種方式配置同時存在,以第二種方式為主。
如果三種方式都存在的時候,以實體類中注解格式為主。
總結(jié)
到此這篇關(guān)于SpringBoot利用jackson格式化時間的文章就介紹到這了,更多相關(guān)SpringBoot jackson格式化時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Apache組件分析對象池原理的實現(xiàn)案例分析
本文從對象池的一個簡單案例切入,主要分析common-pool2組件關(guān)于:池、工廠、配置、對象管理幾個角色的源碼邏輯,并且參考其在Redis中的實踐,對Apache組件分析對象池原理相關(guān)知識感興趣的朋友一起看看吧2022-04-04
Mybatis如何自動生成數(shù)據(jù)庫表結(jié)構(gòu)總結(jié)
這篇文章主要給大家介紹了關(guān)于Mybatis如何自動生成數(shù)據(jù)庫表結(jié)構(gòu)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者使用Mybatis具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
Spring 重定向(Redirect)指南及相關(guān)策略問題
本文介紹了在Spring中實現(xiàn)重定向的三種不同方法,在執(zhí)行這些重定向時如何處理/傳遞屬性以及如何處理HTTP POST請求的重定向。關(guān)于Spring 重定向(Redirect)指南的相關(guān)知識大家參考下本文2017-11-11
java.sql.SQLRecoverableException關(guān)閉的連接異常問題及解決辦法
當(dāng)數(shù)據(jù)庫連接池中的連接被創(chuàng)建而長時間不使用的情況下,該連接會自動回收并失效,就導(dǎo)致客戶端程序報“ java.sql.SQLException: Io 異常: Connection reset” 或“java.sql.SQLException 關(guān)閉的連接”異常問題,下面給大家分享解決方案,一起看看吧2024-03-03

