前端传递Json串中有格式化的日期类型在后端Controller中映射不到的问题

定义的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;

查看结果是正确的了:

 

 

 

posted @ 2019-12-08 19:09  丁茜萌萌哒  阅读(1157)  评论(0编辑  收藏  举报