Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonDeserialize not work for LocalDateTime [duplicate]

Tags:

java

jackson

I would like to send POST request from my client to my backend, and in the POJO I have two fields LocalDate and LocalDateTime as follows:

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy - hh:mm:ss")
private LocalDateTime createdTimestamp;

@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")
private LocalDate expiredDate; 

The client will send request with body like:

{
    "expiredDate" : "01.01.2020",
    "createdTimestamp" : "01.02.2020 - 10:10:10"  
}

In the backend, however, I got an exception:

java.lang.NoSuchMethodError:
com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;

And if I leave the createdTimestamp out of request's body then it worked. It seems that only the annotation @JsonDeserialize(using = LocalDateDeserializer.class) worked, while the @JsonDeserialize(using = LocalDateTimeDeserializer.class) did not work.

Does anyone have an idea why this happened?


1 Answers

You are using the symbol for hours in 12h format (hh) in your pattern, but the pattern is incomplete because it is missing an indicator for AM/PM, which would be an a. Leaving that indicator makes the time expression ambiguous, it could be 10 AM or 10 PM (22 in 24h-format).

You could just switch the format to 24h format (HH), which would make the time unambiguous.

Like this:

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy - HH:mm:ss")
private LocalDateTime createdTimestamp;
like image 129
deHaar Avatar answered Sep 16 '25 08:09

deHaar