定義的Json格式字符串:
{"associationName":"書法社","associationDescribtion":"你喜歡書法嗎,喜歡的話就加入我們吧。","startTime":"2019-12-05 00:00:00","name":"肥宅"}
后端定義的DTO中日期為:
1 @Data 2 public class AssociationDTO { 3 private Integer associationId; 4 private String associationName; 5 private String name; 6 private String associationDescribtion; 7 private Date startTime; 8 }
當在controller中接受前端傳遞的Json串時,會發生異常:
Cannot deserialize value of type `java.util.Date` from String \"2019-12-05 00:00:00\": not a valid representation (error: Failed to parse Date value '2019-12-05 00:00:00': Cannot parse date \"2019-12-05 00:00:00\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String \"2019-12-05 00:00:00\": not a valid representation (error: Failed to parse Date value '2019-12-05 00:00:00': Cannot parse date \"2019-12-05 00:00:00\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))\n at [Source: (PushbackInputStream); line: 1, column: 145] (through reference chain: com.nclg.association_manager.dto.AssociationDTO[\"startTime\"])
解決辦法:
在DTO中加上注解:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date startTime;
再看看結果如何:
雖然沒有格式化處理,而但是可以看出時間是:2019-12-05 8:00:00 ,而我們傳入的Json中的字符串中日期是多少呢:
"startTime":"2019-12-05 00:00:00"
可以看到,傳入到DTO中的時間居然比傳入的時間差了8個小時。這是為什么?
因為,jackson在序列化時間時是按照國際標准時間GMT進行格式化的,而在國內默認時區使用的是CST時區,兩者相差8小時
所以,解決的辦法是再加上一個屬性:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date startTime;
查看結果是正確的了: