QUESTION: Spring apparently uses different deserialization methods for LocalDate depending on whether it is @RequestBody in @RequestBody or @ReqestParam request - is this correct, and if so, is there any way to configure them to be the same throughout the application?
BACKGROUND: In my @RestController , I have two methods: one GET and one POST. GET expects a request parameter ("date") that is of type LocalDate ; POST expects a JSON object in which one key ("date") is of type LocalDate . Their signatures are similar to the following:
@RequestMapping(value = "/entity", method = RequestMethod.GET) public EntityResponse get( Principal principal, @RequestParam(name = "date", required = false) LocalDate date) @RequestMapping(value = "/entity", method = RequestMethod.POST) public EntityResponse post( Principal principal, @RequestBody EntityPost entityPost) public class EntityPost { public LocalDate date; }
I configured my ObjectMapper as follows:
@Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.registerModule(new JavaTimeModule()); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); return objectMapper; }
This ensures that the system accepts LocalDate in the format yyyy-MM-dd and deserializes it as expected, at least when it is part of @RequestBody . So if for post
is the request body:
{ "date": 2017-01-01 }
The system deserializes the request body in EntityPost as expected.
However, this configuration does not apply to @RequestParam deserialization. As a result, this fails:
Instead, the system expects the format to be MM / dd / yy. As a result, it succeeds:
I know I can change this based on parameter by parameter using @DateTimeFormat annotation. I know that if I change the signature of the GET method as follows, it will take the first format:
@RequestMapping(value = "/entity", method = RequestMethod.GET) public EntityResponse get( Principal principal, @RequestParam(name = "date", required = false) @DateTimeFormat(iso=DateTimeFormat.ISO.DATE) LocalDate date)
However, I would prefer that I do not have to include an annotation for every use of LocalDate . Is there a way to set this globally so that the system deserializes every @RequestParam type LocalDate in the same way?
For reference:
I am using Spring 4.3.2.RELEASE
I am using Jackson 2.6.5