问题
异常信息:
Invalid JSON input: Cannot deserialize value of type java.time.LocalDateTime from String “2021-7-21 15:21:13”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2021-7-21 15:21:13’ could not be parsed at index 5; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.LocalDateTime from String “2021-7-21 15:21:13”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2021-7-21 15:21:13’ could not be parsed at index 5\n at [Source: (PushbackInputStream); line: 2, column: 18]
解决
加入配置类.实体类中的字段不要加@JsonFormat注解
/**
* localDateTime反序列化配置
*/
@Configuration
public class LocalDateTimeSerializingConfig {
private String localDateTimeFormat="yyyy-MM-dd HH:mm:ss";
private String localDateFormat="yyyy-MM-dd";
private String localTimeFormat="HH:mm:ss";
@Bean
public ObjectMapper objectMapper() {
ObjectMapper om = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
//序列化
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(localDateTimeFormat)));
javaTimeModule.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern(localDateFormat)));
javaTimeModule.addSerializer(LocalTime.class,
new LocalTimeSerializer(DateTimeFormatter.ofPattern(localTimeFormat)));
//反序列化
javaTimeModule.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(localDateTimeFormat)));
javaTimeModule.addDeserializer(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern(localDateFormat)));
javaTimeModule.addDeserializer(LocalTime.class,
new LocalTimeDeserializer(DateTimeFormatter.ofPattern(localTimeFormat)));
om.registerModule(javaTimeModule);
return om;
}
}

该博客讨论了在处理JSON输入时遇到的 LocalDateTime 类型反序列化异常。异常信息指出无法将字符串 '2021-7-2115:21:13' 转换为 LocalDateTime,原因是格式不匹配。为了解决这个问题,作者提供了一个配置类 LocalDateTimeSerializingConfig,通过自定义 ObjectMapper 并注册 JavaTimeModule 来指定 LocalDateTime 的序列化和反序列化格式,确保日期时间格式为 'yyyy-MM-dd HH:mm:ss'。

5466

被折叠的 条评论
为什么被折叠?



