Cannot convert String to Date on Body request in spring

I have the code below:

DTO:

Class MyDTO { import java.util.Date; private Date dateOfBirth; public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } } 

controller

 public void saveDOB(@RequestBody MyDTO myDTO, HttpServletRequest httprequest, HttpServletResponse httpResponse) { System.out.println("Inside Controller"); System.out.println(myDTO.getDateOfBirth()); } 

JSON request:

 { "dateOfBirth":"2014-09-04", } 

If I send the request as yyyy-mm-dd, it automatically converts to date. output signal in the controller: - dateOfBirth = Thursday, Thursday, 05:30:00 IST 2014

But when I send DateofBirth in dd-mm-yyyy format, it does not convert the string to date automatically. So how can I handle this thing.

JSON request:

 { "dateOfBirth":"04-09-2014", } 

Conclusion: no Output to the console does not even reach the controller.

I tried with @DateTimeFormat but it does not work.

I am using Spring 4.02. Please suggest which annotations we can use.

+6
source share
3 answers

@DateTimeFormat is for form support objects (commands). Your JSON is handled (by default) by Jackson ObjectMapper in Spring MappingJackson2HttpMessageConverter (assuming the latest version of Jackson). This ObjectMapper has a number of default date formats that it can handle. yyyy-mm-dd seems to be one of them, but dd-mm-yyyy not.

You will need to register your date format with ObjectMapper and register this ObjectMapper with MappingJackson2HttpMessageConverter . Here are some ways to do this:

Alternatively, you can use JsonDeserializer either for your entire class, or for one of its fields (dates). Examples in the link below

+12
source

List item Create a class for the JsonDeserializer extension

 public class CustomJsonDateDeserializer extends JsonDeserializer<Date> { @Override public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String date = jsonParser.getText(); try { return format.parse(date); } catch (ParseException e) { throw new RuntimeException(e); } } } 

Use @JsonDeserialize(using = CustomJsonDateDeserializer.class) annotation @JsonDeserialize(using = CustomJsonDateDeserializer.class) for setter methods.

Thanks @Varun Achar answer, url

+1
source

You can use @DateTimeFormat

 @DateTimeFormat(pattern = "dd/MM/yyyy") private Date dateOfBirth; 
0
source

Source: https://habr.com/ru/post/1201739/


All Articles