Cannot deserialize value of type `java.time.LocalDateTime` from String "2023-05-22 17:11:44" 全局配置解决方案
时间: 2023-09-26 16:09:04 浏览: 160
这个问题是因为在反序列化的过程中,无法将字符串 "2023-05-22 17:11:44" 转换为 LocalDateTime 类型。解决方案可以在全局配置文件中配置一个 LocalDateTime 的序列化和反序列化器。
首先,创建一个 LocalDateTime 序列化器:
```java
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(formatter.format(value));
}
}
```
然后,创建一个 LocalDateTime 反序列化器:
```java
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String str = p.getText().trim();
return LocalDateTime.parse(str, formatter);
}
}
```
最后,在全局配置文件中注册这两个序列化器和反序列化器:
```yaml
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
serialization:
write-dates-as-timestamps: false
modules:
- com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
property-naming-strategy: SNAKE_CASE
deserialization:
local-date-time:
date-time-formatter: "yyyy-MM-dd HH:mm:ss"
type: java.time.LocalDateTime
key-deserializer: com.example.LocalDateTimeDeserializer
value-deserializer: com.example.LocalDateTimeDeserializer
creators:
use-big-decimal-for-floats: true
```
这样就可以在反序列化时将字符串转换为 LocalDateTime 类型了。
阅读全文