【问题标题】:LocalDate serialization does not work with spring boot - (@jsonformat dos not work )LocalDate 序列化不适用于 Spring Boot -(@jsonformat 不起作用)
【发布时间】:2021-09-20 14:28:21
【问题描述】:

我正在尝试将 JSON 解析为本地日期,我尝试了多个选项,包括 @jsonFormat 但我仍然收到以下异常 - (我正在使用 spring boot rest 控制器来接受此请求)

public class Student {
    private long rollNumber;
    private String firstName;
    private String lastName;
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    private LocalDate dob;
    private Gender gender;
    private Grade grade;
}

json:

[{
"rollNumber":"1",
"firstName":"abc",
"lastName":"ere",
"dob":"08-06-1993",
"gender":"MALE",
"grade":"TENTH"

}]
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDate` from String \"08-06-1993\": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '08-06-1993' could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDate` from String \"08-06-1993\": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '08-06-1993' could not be parsed at index 0\n at [Source: (PushbackInputStream); line: 5, column: 7] (through reference chain: java.util.ArrayList[0]->com.example.application.restApp.model.Student[\"dob\"])\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:389)\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:342)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:185)\r\n\tat 

【问题讨论】:

标签: json spring-boot jackson-databind


【解决方案1】:

JSON 无法从字符串中反序列化时间。更改日期类型和格式如下。

@JsonFormat
  (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
public Date dob;

【讨论】:

  • 已添加但仍然面临同样的问题...顺便说一句,这些不是来自我们已经添加的 Spring Boot 依赖项
  • 如果上述方法不起作用,请尝试升级最新的 json 依赖版本。
【解决方案2】:

我发现了这个问题,似乎当我们没有 no args 构造函数时,即使 @jsonFormat 似乎也不起作用。我正在使用 Lombok,但在添加问题已解决后,我错过了添加 no args constructor 。 感谢大家的帮助。

有趣的是,spring boot 不会抛出错误,说明 no args 构造函数不存在并尝试执行默认实现。

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 2018-05-30
    • 2015-09-01
    • 2016-11-16
    • 2015-04-13
    • 2018-10-18
    • 2018-03-21
    • 2023-03-20
    • 2021-05-29
    相关资源
    最近更新 更多