I've built a REST endpoint using Spring Boot. JSON
is posted to the endpoint. Jackson converts the JSON
giving me an object.
The JSON
look like this:
{
"parameterDateUnadjusted": "2017-01-01",
"parameterDateAdjusted": "2017-01-02"
}
Jackson converts the JSON
to an object based on this class:
public class ParameterDate {
@NotNull(message = "Parameter Date Unadjusted can not be blank or null")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date parameterDateUnadjusted;
@NotNull(message = "Parameter Date Adjusted can not be blank or null")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date parameterDateAdjusted;
private Date parameterDateAdded;
private Date parameterDateChanged;
}
This all works fine. The issue I'm having is that I would like to validate the data before Jackson converts the data. For instance if I post
{
"parameterDateUnadjusted": "2017-01-01",
"parameterDateAdjusted": "2017-01-40"
}
Where parameterDateAdjusted
is not a valid date (there is no month with 40 days in it). Jackson converts this to 2017-02-09
. One way of getting around this is to have a class that is only strings let's call it ParameterDateInput
. Validate each filed with Hibernate Validator in the parameterDateInput
object and then copy the parameterDateInput
object to parameterDate
where each field has the correct type (dates are of type Date
and not of type String
). This to me doesn't look like a very elegant solution. Is there some other way I can solve this? How is data generally validated in Spring Boot when posted as JSON
? I like to be able to send back a message to the user/client what is wrong with the data that is being posted.