I am trying to use Java 8 LocalTime as an attribute in a request object. It seems JSON parsing is not working properly and I get a HTTPStatus 400. My model object:
import java.time.LocalTime;
public class Location {
private String name;
private LocalTime openTime;
....
}
I am using Swagger to document and use the REST apis. This is how the model object looks in Swagger.
{
"name": "string",
"openTime": {
"hour": 8,
"minute": 0,
"nano": 0,
"second": 0
}
}
I am using JSR310 dependency for jackson
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Spring Boot version is 1.5.9.RELEASE
I have the following questions:
How do I make the parsing work?
I just need hour and minute. How can I configure it?
How do I get more detail about the nature of the exception here. My application logs are clean. I have an RestControllerAdvice configured for exception handling, which does not handle it
@RestControllerAdvice public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{ @ExceptionHandler({ JsonMappingException.class }) @ResponseStatus(HttpStatus.BAD_REQUEST) public List<ApplicationErrorDto> handle(JsonMappingException exception) { ApplicationErrorDto applicationErrorDto = new ApplicationErrorDto(); applicationErrorDto.setMessage("Request body is malformed"); logger.info("Request body is malformed: " ,exception); return Arrays.asList(applicationErrorDto); } //methods for other exceptions }
I tried following a similar link, but unable to solve it for myself so far: JSON Java 8 LocalDateTime format in Spring Boot
EDIT-1------------------------------------------------------------
I took @JBNizet's advice, returned Locatime from an controller(not an object containing LocalTime). This is what I get:
[
13,
42,
38,
550000000
]
That's my local time. Then I used the following property in application.properties
spring.jackson.serialization.write_dates_as_timestamps=false
Using the property helped me to change the localtime to a more readable format: "13:48:04.207"
However, a POST endpoint that expects a LocalTime object, is interpreted by Swagger as:
{
"hour": 0,
"minute": 0,
"nano": 0,
"second": 0
}
Using this schema to POST a LocalTime throws the same 400 error. So, I just copied the structure I was getting in my GET URL and it started working. Both of the following work:
"13:48:04.207"
"13:48"