不會自動轉換string與date
主要是這個意思,前端提交的JSON里,日期是一個字符串,而對應后端的實體里,它是一個Date的日期,這兩個在默認情況下是不能自動轉換的,我們先看一下實體
實體
1
2
3
4
5
6
7
8
|
private String name; private String email; private Boolean sex; private Double total; private BigDecimal totalMoney; private Date birthday; } |
客戶端提交的json對象
1
2
3
4
5
6
7
|
{ "email" : null , "name" : "lr" , "total" : 3 , "totalMoney" : 1 , "birthday" : "1983-03-18" } |
服務端收到的實體DTO是正常的
而在服務端響應的結果卻不是日期,而是一個時間戳
1
2
3
4
5
6
7
8
|
{ "name" : "lr" , "email" : null , "sex" : null , "total" : "3.00" , "totalMoney" : 0.0000 , "birthday" : 416793600000 } |
我們看到日期型的birthday在響應到前端還是一個時間戳,如果我們希望響應到前端是一個日期,那需要為這個DTO實體添加JsonFormat
注解
1
2
3
4
5
6
7
8
9
|
public class UserDTO { private String name; private String email; private Boolean sex; private Double total; private BigDecimal totalMoney; @JsonFormat (pattern = "yyyy-MM-dd" , timezone = "GMT+8" ) private Date birthday; } |
也可以通過配置文件進行設置
1
2
3
4
|
spring: jackson.date-format: yyyy-MM-dd jackson.time-zone: GMT+ 8 jackson.serialization.write-dates-as-timestamps: false |
這樣,在服務端向前端響應結果就變成了
使用configureMessageConverters方法全局處理
springboot2.x可以實現WebMvcConfigurer 接口,然后重寫configureMessageConverters來達到定制化日期序列化的格式:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Configuration @EnableWebMvc //覆蓋默認的配置 public class WebMvcConfigurerImpl implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); // 時間格式化 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false ); objectMapper.setDateFormat( new SimpleDateFormat( "yyyy-MM-dd" )); //只能是一個日期格式化,多個會復蓋 } } |
如上圖所示,如果希望為getup
字段添加時分秒,需要在DTO上使用@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
注解即可。
總結
到此這篇關于springboot~DTO字符字段與日期字段的轉換問題的文章就介紹到這了,更多相關springboot字符字段與日期字段轉換內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/lori/archive/2020/07/17/13330141.html