今天开发项目中,报出了如下的异常,java
org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Can not deserialize value of
type java.util.Date from String "2018-10-17 18:43:02":
not a valid representation
(error: Failed to parse Date value '2018-10-17 18:43:02':
Can not parse date "2018-10-17 18:43:02Z":
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-17 18:43:02": not a valid representation
(error: Failed to parse Date value '2018-10-17 18:43:02':
Can not parse date "2018-10-17 18:43:02Z":
while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'',
parsing fails (leniency? null))
复制代码
从异常能够知道,是由于Date字段反序列化过程当中,格式非法,致使转换错误。SpringBoot中默认JSON转换是使用Jackson,而后Jackson支持以下几种日期格式。spring
可是咱们经常使用的是yyyy-MM-dd HH:mm:ss
,因此须要转换格式。bash
我以前已经在配置文件中定义了app
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
复制代码
因此在使用在写JsonUtil时出现上面的异常,我查了资料,有人建议全局配置工具
@Configuration
public class JacksonConfig {
@Bean
public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
//设置日期格式
ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(smt);
mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
return mappingJackson2HttpMessageConverter;
}
}
复制代码
上述的配置并不可以解决问题,而后我查看源码发现,实际上是ObjectMapper
里面定义了默认格式,因此工具类的时候才把格式转换ui
private final static ObjectMapper mapper = new ObjectMapper();
static {
mapper.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(format);
}
复制代码
上述配置就解决问题,可是这个并不适用于其余的ObjectMapper
。试了不少配置都没有效果,最后用了最简单的方式便可解决spa
@JsonFormat( pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
复制代码
直接用注解完美解决。code