今天用API接口测试SpringBoot项目遇到这样的错误:
JSON parse error:Cannot deserialize value of type `java.time.LocalDateTime`
from String "2019-09-25 05:43:00":Failed to deserialize java.time.LocalDateTime:(java.time.format.DateTimeParseException)
Text '2019-09-25 05:43:00'could not be parsed at index 10; nested exception is
com.fasterxml.jackson.databind.exc.InvalidFormatException:
Cannot deserialize value of type`java.time.LocalDateTime`
from String "2019-09-25 05:43:00": Failed to deserialize java.time.LocalDateTime:(java.time.format.DateTimeParseException)
Text '2019-09-25 05:43:00' could not be parsed at index 10
后来查了一下原因,记录一下
原因是实体类中参数类型为LocalDateTime, 但是Postman测试的json格式的数据是String字符串。
只需要在接收参数实体类的日期字段上添加JsonFormat注解即可
补充个内容:
@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss” timezone = “GMT+8”)
转化时区差
字符串类型直接转换成Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(new Date());