zl程序教程

您现在的位置是:首页 >  其它

当前栏目

@DateTimeFormat、@JsonFormat、@JSONField

2023-09-14 09:00:00 时间

今天在处理时间时遇到

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2020-04-08": expected format "yyyy-MM-dd HH:mm:ss"; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2020-04-08": expected format "yyyy-MM-dd HH:mm:ss"

属性

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startDate;

前端传过来的,只有年月日,需要的格式为yyyy-MM-dd HH:mm:ss

解决的方法

将前端的日期格式改为

yyyy-MM-dd  HH:mm:ss

或者修改属性的注解里pattern的值

@JsonFormat(pattern = "yyyy-MM-dd")
private Date startDate;

补充:

1.@DateTimeFormat

spring自带的,将String转换成Date,一般前台给后台传值时用

@DateTimeFormat(pattern=”yyyy-MM-dd”)

2.@JsonFormat

来源于jackson,将Java对象转换成json对象和xml文档,或将json、xml转换成Java对象

主要用于后台传值到前台

在属性值上

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")

3.@JSONField

来源于fastjson,主要进行JSON解析和序列化

@JSONField(format = "yyyy-MM-dd HH:mm:ss")