蒙国造博客

解决 Jackson 解析错误:Cannot deserialize value of type `java.time.LocalDateTime` from String … could not be parsed at index 10

详细错误如下:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2020-08-11 11:00:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2020-08-11 11:00:00' could not be parsed at index 10

这是因为用了 JavaTimeModule() 作为 localDatelocalDateTime 的解析工具,但是对于日期和时间格式我们没有指定,所以会使用默认的格式,也就是:DateTimeFormatter.ISO_LOCAL_DATE_TIME,就是类似这样的:2011-12-03T10:15:30

假设我们自己用的格式是2020-08-11 11:00:00,就需要手动配置格式:

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
        objectMapper.registerModule(javaTimeModule);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

参考资料:

退出移动版