PROBLEM
Given the following controller …
@RestController @RequestMapping(value = '/controller') class MyController { @RequestMapping(method = RequestMethod.GET) ResponseEntity main(@RequestParam(name = 'dateTime') LocalDateTime dateTime) { // ... return ResponseEntity.noContent().build() } }
When executing …
GET https://localhost:8443/controller?dateTime=2017-06-22T17:38
… the web service call returns 400 Bad Request with the following error in the console log:-
Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDateTime] for value '2017-06-22T17:38'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2017-06-22T17:38]
SOLUTION
One solution is to change the data type from java.time.LocalDateTime
to java.lang.String
before parsing it to java.time.LocalDateTime
. However, it is a little more verbose than I like.
A better way is to leverage @DateTimeFormat
:-
@RestController @RequestMapping(value = '/controller') class MyController { @RequestMapping(method = RequestMethod.GET) ResponseEntity main(@RequestParam(name = 'dateTime') @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") LocalDateTime dateTime) { // ... return ResponseEntity.noContent().build() } }
Simillary iam facing
“Failed to convert value of type [java.lang.String] to required type [int]; nested exception is java.lang.NumberFormatException: For input string: ‘updateTable’ “. pls help me guyz
This works well for date patterns that don’t have timestamp, but if your pattern includes a timestamp, it will fail to parse a String formatted correctly with timestamp.
Just wanted to say thank you and this solved my issue with Date serialization. Thank you for the effort in making this post.