2025-10-18 00:57:23.131 ERROR 60896 --- [nio-8123-exec-6] c.y.c.exception.GlobalExceptionHandler : RuntimeException:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Cannot deserialize value of type `java.util.Date` from String "2025-10-18 00:52:00":
not a valid representation (error: Failed to parse Date value '2025-10-18 00:52:00':
Cannot parse date "2025-10-18 00:52:00": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null));
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException:
Cannot deserialize value of type `java.util.Date` from String "2025-10-18 00:52:00":
not a valid representation (error: Failed to parse Date value '2025-10-18 00:52:00':
Cannot parse date "2025-10-18 00:52:00":
while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))
at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 12, column: 16]
(through reference chain: com.yu.cloudpicturebackend.model.dto.picture.PictureQueryRequest["beginTime"])
原先请求类时间字段使用 Date 格式,这个错误是因为 日期格式不匹配 导致的。Jackson 无法将字符串 "2025-10-18 00:52:00" 解析为 java.util.Date 类型。
问题分析
错误信息显示:
- 期望的格式:
yyyy-MM-dd'T'HH:mm:ss.SSSX(ISO 8601 格式) - 实际传入的格式:
yyyy-MM-dd HH:mm:ss(空格分隔)
解决方案
方案1:给字段添加注解
在请求类的字段上添加注解
在 PictureQueryRequest 类的 beginTime 字段上添加日期格式注解,使前端传来的时间能被正确解析为北京时间:
java
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class PictureQueryRequest {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime beginTime;
// 其他字段...
// getter 和 setter
}
在返回的VO类的字段上添加注解
在 PictureVO 类的 createTime 字段上添加日期格式注解,
避免:序列化时 Jackson 将 LocalDateTime 当作 无时区信息 的时间,可能按系统默认时区(UTC)序列化
@Data
public class BaseModel implements Serializable {
private static final long serialVersionUID = 1922399947283616441L;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;
/**
* 编辑时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime editTime;
/**
* 更新时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime updateTime;
}
方案2:全局配置日期格式
- 如果封装的请求类日期字段都是使用的 Date 格式,即可直接使用下面的全局配置
在 application.yml中配置:
application.yml:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8