SpringBoot中的Jackson中日期反序列化問題

今天開發項目中,報出瞭如下的異常,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'T'HH:mm:ss.SSSZ
  • yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
  • yyyy-MM-dd
  • EEE, dd MMM yyyy HH:mm:ss zzz

可是咱們經常使用的是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

相關文章
相關標籤/搜索