Home > other >  Proper way to automatically deserialise a LocalDateTime request param in Spring Boot 3
Proper way to automatically deserialise a LocalDateTime request param in Spring Boot 3

Time:12-13

What is the proper (recommended/documented) way to automatically deserialise a LocalDateTime request param in Spring Boot 3.

The url looks like http://localhost:8080/test?from=20221001000000

I have tried this solution and it does not work

@RequestMapping("/test")
public String index(@DateTimeFormat(pattern = "YYYYMMddHHmmss") java.time.LocalDateTime from) {
.....
}

I have tried this and it does not work neither. It does not even enter the custom deserialiser.

@RequestMapping("/test")
public String index(@JsonDeserialize(using = LocalDateTimeDeserializer.class) LocalDateTime from) {
........
}

@Override
public LocalDateTime deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JacksonException {
        ....
    }

The exception that I get is

[org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' from required type 'java.time.LocalDateTime'; Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '20221001000000']

CodePudding user response:

It seems your pattern is not correct, try this instead:

uuuuMMddHHmmss
  • uuuu for the year
  • MM for the month month
  • dd for the day
  • HH for an hours in a 24-hour format
  • mm for minutes
  • ss for seconds

Your code can look like this

@RequestMapping("/test")
public String index(@DateTimeFormat(pattern = "uuuuMMddHHmmss") LocalDateTime from) {
    ...
}

CodePudding user response:

DateTimeFormat should be "y" for Year and not "Y". See the DateTimeFormat ISO format documentation:

https://docs.spring.io/spring-framework/docs/3.0.x/javadoc-api/org/springframework/format/annotation/DateTimeFormat.ISO.html

  • Related