There is a Date of birth property in my request POJO which is String. In my response POJO, date of birth property is joda's DateTime. I converted it into DateTime by using "new DateTime(requestModel.getDateOfBirth())". Though, it is only accepting the date format(which is in String) as "yyyy-mm-dd". When I change the request date format, it throws "500
Blockquote
". Here is my POJOs:
RequestModel.java
public class RequestModel {
@NotNull(message = "dateOfBirth cannot be null")
private String dateOfBirth;
public RequestModel(String dateOfBirth) {
super();
this.dateOfBirth = dateOfBirth;
}
public String getDateOfBirth() {
return dateOfBirth;
}
}
ResponseModel.java
public class ResponseModel {
private DateTime dateOfBirth;
public ResponseModel( DateTime dateOfBirth) {
super();
this.dateOfBirth = dateOfBirth;
}
public DateTime getDateOfBirth() {
return dateOfBirth;
}
}
MyController.java
@PostMapping(consumes = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE
},
produces = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE
})
public ResponseEntity<ResponseModel> create(@Valid @RequestBody RequestModel requestModel) {
ResponseModel response = new ResponseModel(new DateTime(requestModel.getDateOfBirth()));
return new ResponseEntity<ResponseModel>(response, HttpStatus.CREATED);
}
This is the post JSON request which works fine:
{
"dateOfBirth" : "2012-12-12"
}
The following request body throws error:
{
"dateOfBirth" : "12-12-2012",
}
The error is:
{
"timestamp": "2020-03-14T19:09:51.647+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Invalid format: \"12-12-2012\" is malformed at \"12\"",
"path": "/myPath/"
}
I want to know how can I improve the controller logic or the design to accept any Date format in the API? Thanks for helping out