Springboot框架下Date类型数据上传问题

问题场景:

使用Springboot框架搭建服务,实现如下需求, 服务端使用实体类接收客户端上传具有相同结构的json数据信息,其中实体类的属性字段中包含java.util.Date类型的属性字段。

问题描述:

1.由客户端上传的json数据中Date字段格式为“2016-08-15 17:00:00”,测试调用时报如下错误:

{
  "timestamp": 1521217111334,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
  "message": "JSON parse error: Can not deserialize value of type java.util.Date from String \"2016-08-15 17:00:00\": not a valid representation (error: Failed to parse Date value '2016-08-15 17:00:00': Can not parse date \"2016-08-15 17:00:00\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.Date from String \"2016-08-15 17:00:00\": not a valid representation (error: Failed to parse Date value '2016-08-15 17:00:00': Can not parse date \"2016-08-15 17:00:00\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS', parsing fails (leniency? null))\n at [Source: java.io.PushbackInputStream@6317f037; line: 9, column: 11] (through reference chain: com.consmation.iwebmapserver.projectserver.model.BusGeologicalDrilling[\"fixdt\"])",
  "path": "/MobileServer/SaveGeologicalDrillingInfo"
}

该错误大意为:不能解析日期\“2016-08-15 17:00:00 \”:虽然它似乎符合格式的yyyy-MM-dd 'HH:mm:ss.SSS”

2.此时将上传的Date数据修改为 2016-08-15T16:00:00 ,程序虽不再报错误,但是通过跟踪程序实体类发现,该字段的值为:2016-08-16 1:00:00,不符合我们所上传的日期。

错误分析:

1. Springboot使用的默认json解析框架是jackjson框架

2. jackjson解析框架在解析实体类里面是date数据类型的数据时的默认格式是:UTC类型,即yyyy-MM-dd'T'HH:mm:ss.SSS 并且默认为+8时区,即时间基础上加8小时

解决方案:

1. 在实体Date类型的字段上使用@JsonFormat注解格式化日期 

@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
2. 通过下面方式取消timestamps形式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

备注:

如果项目中使用json解析框架为 fastjson框架,则可使用如下解决方法:
1. 在实体字段上使用@JsonFormat注解格式化日期
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")

猜你喜欢

转载自blog.csdn.net/pp_fzp/article/details/79588374