当前位置: 首页 > 其他程序 > 正文

解决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);

本文固定链接: https://www.ziyouwu.com/archives/29992.html | 自由屋博客


关键字: