赞
踩
问题描述:
由客户端上传的json数据中Date字段格式为“2018-10-25 15:58:31”,测试调用时报如下错误:
org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Can not deserialize value of type java.util.Date from String
"2018-10-25 15:58:31": not a valid representation (error: Failed to parse Date value '2018-10-25 15:58:31': Can not parse date "2018-10-25 15:58:31Z": while it seems to
fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null)); nested
exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not
deserialize value of type java.util.Date from String "2018-10-25 15:58:31": not a valid
representation (error: Failed to parse Date value '2018-10-25 15:58:31': Can not
parse date "2018-10-25 15:58:31Z": while it seems to fit format 'yyyy-MM-
dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null))
错误分析:
Springboot使用的默认json解析框架是jackjson框架
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框架,则可使用如下解决方法:
在实体字段上使用@JsonFormat注解格式化日期
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。