问题描述:
由客户端上传的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))

错误分析:

  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框架,则可使用如下解决方法:
在实体字段上使用@JsonFormat注解格式化日期

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 2 个月前
8c391e04 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐