简体   繁体   English

如何用杰克逊解析 LocalDate

[英]How to parse LocalDate with Jackson

I am facing problem passing date as json data through postman.我面临通过邮递员将日期作为 json 数据传递的问题。 In case of Mandetory date with @NotNull annotation, no problem.如果 Mandetory 日期带有@NotNull注释,没问题。 The other date is accepting null.另一个日期接受空值。 But at the time of updation, that date creates problem.但是在更新时,该日期会产生问题。 I am using Java 1.8 with spring boot & MySql DB.我正在使用带有 Spring Boot 和 MySql DB 的 Java 1.8。 Please help请帮忙

The following links I have visited, but does not fit with this.我访问过以下链接,但不适合此。 LocalDateTime parsing with jackson JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value https://stackoverflow.com/a/29959842/3415090 JSON Java 8 LocalDateTime format in Spring Boot 使用杰克逊JSON 解析错误进行 LocalDateTime 解析:无法构造 java.time.LocalDate 的实例:没有从字符串值反序列化的字符串参数构造函数/工厂方法https://stackoverflow.com/a/29959842/3415090 JSON Java 8 LocalDateTime 格式在 Spring Boot 中

I have also used我也用过

@JsonSerialize(using = LocalDateSerializer.class)
@JsonDeserialize(using = LocalDateDeserializer.class)

But problem remains as it is.但问题仍然存在。

My UX我的用户体验

public class LeaveApplUx {

    @JsonIgnore
    @Size(max = 5, message = "Employee Code Must Be Within 4 To 5 Character Long Or Blank")
    private final String employeeCode;

    @NotNull(message = "Start Date Empty")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    private final LocalDate startDate;

    @JsonIgnore
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    private final LocalDate rejoinDate;

    public LeaveApplUx(
            @Size(min = 4, max = 5, message = "Employee Code Must Be Within 4 To 5 Character Long Or Blank") 
        @JsonProperty("employeeCode") String employeeCode,
            @NotNull(message = "Start Date Empty") @JsonProperty("startDate") LocalDate startDate,
            @JsonProperty("rejoinDate") LocalDate rejoinDate) {
        this.employeeCode = employeeCode;
        this.startDate = startDate;
        this.rejoinDate = rejoinDate;
    }
//  GETTERS
}

At the time of creation, it works fine.在创建时,它工作正常。

{
    "employeeCode": "B426",
    "startDate": "01-03-2023"
}

Input Parameters : {"employeeCode":"B426","startDate":{"year":2023,"month":"MARCH","monthValue":3,"dayOfMonth":1,"leapYear":false,"dayOfWeek":"WEDNESDAY","dayOfYear":60,"era":"CE","chronology":{"id":"ISO","calendarType":"iso8601"}},"rejoinDate":null} Record saved properly in DB输入参数: {"employeeCode":"B426","startDate":{"year":2023,"month":"MARCH","monthValue":3,"dayOfMonth":1,"leapYear":false,"dayOfWeek":"WEDNESDAY","dayOfYear":60,"era":"CE","chronology":{"id":"ISO","calendarType":"iso8601"}},"rejoinDate":null}记录正确保存在数据库中

But at the time of updation, it creates error.但是在更新时,它会产生错误。

{
    "employeeCode": "B426",
    "startDate": "01-03-2023",
    "rejoinDate": "06-03-2023"
}

JSON parse error: 

Cannot deserialize value of type `java.time.LocalDate` from String "06-03-2023": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '06-03-2023' 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 "06-03-2023": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '06-03-2023' could not be parsed at index 0
     at [Source: (PushbackInputStream); line: 14, column: 19] (through reference chain: org.myapp.ux.hr.leave.LeaveApplUx["rejoinDate"])

Since you set values through contructor, not setters, you should put @JsonFormat(...) on constructor parameters, not fields.由于您通过构造函数而不是设置器设置值,因此您应该将@JsonFormat(...)放在构造函数参数上,而不是字段上。 This should fix it:这应该解决它:

public class LeaveApplUx {

    @JsonIgnore
    private final String employeeCode;

    private final LocalDate startDate;

    @JsonIgnore
    private final LocalDate rejoinDate;

    public LeaveApplUx(@JsonProperty("employeeCode") String employeeCode,
                       @JsonProperty("startDate") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") LocalDate startDate,
                       @JsonProperty("rejoinDate") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") LocalDate rejoinDate) {
        this.employeeCode = employeeCode;
        this.startDate = startDate;
        this.rejoinDate = rejoinDate;
    }

    //getters
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM