解决:Cannot deserialize value of type `java.util.Date` from String “xxx“: not a valid representation..

一、问题:

        在做数据更新操作的时候,后台数据为Date时,前端把String类型数据传到后台时,Date类型无法识别这个String数据,所以会报错。

二、错误描述: 

 主要问题:

Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2019-10-08": not a valid representation (error: Failed to parse Date value '2019-10-08': Unparseable date: "2019-10-08")
 at [Source: (PushbackInputStream); line: 1, column: 727] (through reference chain: com.wph.service.edu.entity.Teacher["joinDate"])

 三、解决方法:

        在实体类中的Data类型数据加上@JsonFormat注解,先来看一下这个注解的属性,我们常用的有timezone{时区}pattern(图案)

 部分源码:

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonFormat {
    String DEFAULT_LOCALE = "##default";
    String DEFAULT_TIMEZONE = "##default";

    String pattern() default "";

    JsonFormat.Shape shape() default JsonFormat.Shape.ANY;

    String locale() default "##default";

    String timezone() default "##default";

    OptBoolean lenient() default OptBoolean.DEFAULT;

    JsonFormat.Feature[] with() default {};

    JsonFormat.Feature[] without() default {};

使用:

    @JsonFormat(timezone = "UTC",pattern="yyyy-MM-dd")
    private Date joinDate;

猜你喜欢

转载自blog.csdn.net/m0_56233309/article/details/127017142
今日推荐