JSON解析错误 “Cannot deserialize value of type
java.time.LocalDateTime
from String” 通常发生在尝试将JSON字符串转换为Java对象时,而JSON字符串中的日期时间格式与Java中
java.time.LocalDateTime
类期望的格式不匹配。
问题分析
Java中的java.time.LocalDateTime
类表示没有时区信息的日期和时间。当使用诸如Jackson这样的库将JSON转换为Java对象时,库会尝试根据预设的日期时间格式来解析JSON中的字符串。如果JSON字符串中的日期时间格式与预期不匹配,就会出现解析错误。
报错原因
报错原因可能包括:
- JSON中的日期时间字符串格式不正确。
- 没有为JSON解析器配置正确的日期时间格式。
下滑查看解决方法
解决思路
解决这个问题的思路如下:
- 检查JSON格式:确保JSON中的日期时间字符串格式正确。
- 配置日期时间格式:为JSON解析器(如Jackson)配置正确的日期时间格式。
解决方法
方法一:调整JSON中的日期时间格式
如果可能,调整JSON中的日期时间格式以匹配Java中LocalDateTime
的默认格式,通常为ISO 8601格式(例如:yyyy-MM-dd'T'HH:mm:ss
)。
方法二:使用@JsonFormat
注解配置日期时间格式
在Java类的字段上使用@JsonFormat
注解来指定日期时间格式。
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;
public class MyEntity {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime myDateTime;
// getters and setters
}
在这个例子中,我们指定了JSON字符串应该匹配yyyy-MM-dd HH:mm:ss
这种格式。
方法三:配置ObjectMapper
如果你使用的是Jackson库,你可以配置ObjectMapper
来全局地设置日期时间格式。
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class JsonConfig {
public static ObjectMapper configureObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
objectMapper.registerModule(javaTimeModule);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
在这个例子中,我们创建了一个自定义的LocalDateTimeSerializer
,并将其注册到JavaTimeModule
中。这样,当ObjectMapper
解析包含日期时间的JSON时,它会使用我们指定的格式。
代码示例
以下是一个使用ObjectMapper
配置和@JsonFormat
注解的完整示例:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.IOException;
import java.time.LocalDateTime;
public class JsonParseExample {
public static void main(String[] args) {
String json = "{\"myDateTime\":\"2023-03-15 10:30:00\"}";
ObjectMapper objectMapper = new ObjectMapper();
try {
MyEntity entity = objectMapper.readValue(json, MyEntity.class);
System.out.println(entity.getMyDateTime());
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyEntity {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime myDateTime;
// getters and setters
public LocalDateTime getMyDateTime() {
return myDateTime;
}
public void setMyDateTime(LocalDateTime myDateTime) {
this.myDateTime = myDateTime;
}
}