不會自動轉換string與date
主要是這個意思,前端提交的JSON里,日期是一個字符串,而對應后端的實體里,它是一個Date的日期,這兩個在默認情況下是不能自動轉換的,我們先看一下實體
實體
public class UserDTO {
private String name;
private String email;
private Boolean sex;
private Double total;
private BigDecimal totalMoney;
private Date birthday;
}
客戶端提交的json對象
{
"email": null,
"name": "lr",
"total":3,
"totalMoney":1,
"birthday":"1983-03-18"
}
服務端收到的實體DTO是正常的
而在服務端響應的結果卻不是日期,而是一個時間戳
{
"name": "lr",
"email": null,
"sex": null,
"total": "3.00",
"totalMoney": 0.0000,
"birthday": 416793600000
}
我們看到日期型的birthday在響應到前端還是一個時間戳,如果我們希望響應到前端是一個日期,那需要為這個DTO實體添加JsonFormat注解
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;
}
也可以通過配置文件進行設置
spring:
jackson.date-format: yyyy-MM-dd
jackson.time-zone: GMT+8
jackson.serialization.write-dates-as-timestamps: false
這樣,在服務端向前端響應結果就變成了
使用configureMessageConverters方法全局處理
springboot2.x可以實現WebMvcConfigurer 接口,然后重寫configureMessageConverters來達到定制化日期序列化的格式:
Configuration
@EnableWebMvc //覆蓋默認的配置
public class WebMvcConfigurerImpl implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List> 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")注解即可。