controller中接受时间类型异常
- 最近在与后端联调中发现在传入时间为字符串时候后端无法接受字符串类型数据,翻出自己以前的Java代码对比记录一下!
错误信息:
2021-01-15 14:07:46.506 WARN 18224 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2021-01-15 12:12:00": not a valid representation (error: Failed to parse Date value '2021-01-15 12:12:00': Cannot parse date "2021-01-15 12:12: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 "2021-01-15 12:12:00": not a valid representation (error: Failed to parse Date value '2021-01-15 12:12:00': Cannot parse date "2021-01-15 12:12:00": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))
- 前端传入数据
伪代码
beginTime:"2021-01-15 12:12:00"
- 后端定义
private Date beginTime;
处理方式
1.处理方式一:
js中对beginTime字段转换为Date类型
beginTime:new Date(this.account.beginTime)
- 处理方式二:
Java entity对象中data字段添加@JsonFormat注解
@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-mm-dd HH:mm:ss")
private Date beginTime;
- 处理方式三:
全局处理(处理方式未验证),在application.yml文件中全局配置
spring:
jackson:
#字符串时间,用这行表示
date-format: yyyy-MM-dd
#设置为东八区时间
timezone: GMT+8
serialization:
#使用数值timestamp表示日期
write-dates-as-timestamps: true
#想要值为2019-01-01
write-dates-as-timestamps: false