'LocalDate cannot be mapping in spring @RestController
The following example works for a POST request, but not for GET. My goal is to let spring automatically parse LocalDate from String input (both request body and also query parameter):
@PostMapping("/datetime")
public Mono<String> datetimePost(@RequestBody DateTimeDto dto) {
return Mono.just("OK");
}
static class DateTimeDto {
private LocalDate date;
//getter, setter
}
Works: POST localhost:8080/datetime
{
"date": "2022-02-02"
}
But the same does not wor with GET:
GET localhost:8080/datetime?date=2022-02-02
@GetMapping("/datetime")
public Mono<String> datetimeGet(DateTimeDto dto) {
return Mono.just("OK);
}
Result:
{
"timestamp": "2022-03-03T08:57:56.248+00:00",
"status": 400,
"message": "'date': : Parse attempt failed for value [2022-02-02]. rejectedValue: 2022-02-02"
}
org.springframework.web.bind.support.WebExchangeBindException: Validation failed for argument at index 0 in method: public reactor.core.publisher.Mono<java.lang.Object> org.example.spring.webflux.ExampleServlet.datetimeGet(org.example.spring.webflux.ExampleServlet$DateTimeDto), with 1 error(s): [Field error in object 'dateTimeDto' on field 'date': rejected value [2022-02-02]; codes [typeMismatch.dateTimeDto.date,typeMismatch.date,typeMismatch.java.time.LocalDate,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [dateTimeDto.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '2022-02-02'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-02-02]]] at org.springframework.web.reactive.result.method.annotation.ModelAttributeMethodArgumentResolver.lambda$null$3(ModelAttributeMethodArgumentResolver.java:139) ~[spring-webflux-5.3.16.jar:5.3.16]
Solution 1:[1]
So as the way GET + POST works is different, the following fixes the problem at least:
application.properties:
spring.webflux.format.date=ISO
spring.webflux.format.time=ISO
spring.webflux.format.date-time=ISO
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | membersound |
