Cannot deserialize value of type `java.util.Date` from String "2019-5-31 00:00": not a valid represe

异常完整信息

java.lang.IllegalArgumentException: Cannot deserialize value of type `java.util.Date` from String "2019-5-31 00:00": not a valid representation (error: Failed to parse Date value '2019-5-31 00:00': Cannot parse date "2019-5-31 00:00": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))

异常场景:

前端传的时间格式是yyyy-MM-dd HH:mm

服务器的controller接收方式:@RequestBody Map<String, Object> param

然后将map转成实体集合,代码如下

   List<xxx> list1 = (List<xxx>) map.get("jsonStr");
   ObjectMapper mapper = new ObjectMapper();
   List<xxx> list = mapper.convertValue(list1, new TypeReference<List<xxx>>(){ });

异常描述:

jackson反序列化失败,yyyy-MM-dd HH:mm不是有效的格式。

这里提下jackson默认支持的日期反序列格式:

("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

解决方案:重写jackson反序列化

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JsonDateDeserializer extends JsonDeserializer {
    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = p.getText();
        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

 

 

 

 

你可能感兴趣的:(开发遇到错误)