Unable to convert String to Date by requestBody in spring

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

I have the below Code :

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 automatic conversion to date object happens. output in controller:- dateOfBirth= Thu Sep 04 05:30:00 IST 2014

But when I send DateofBirth in dd-mm-yyyy format It does not convert String to Date automatically.So how i can i handle this case.

JSON Request :

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

Output: No Output in console does not even reaches controller.

I have tried with @DateTimeFormat but its not working.

I am using Spring 4.02 Please suggest is there any annotation we can use.

回答1:

@DateTimeFormat is for form backing (command) objects. Your JSON is processed (by default) by Jackson's ObjectMapper in Spring's MappingJackson2HttpMessageConverter (assuming the latest version of Jackson). This ObjectMapper has a number of default date formats it can handle. It seems yyyy-mm-dd is one of them, but dd-mm-yyyy is not.

You'll need to register your own date format with a ObjectMapper and register that ObjectMapper with the MappingJackson2HttpMessageConverter. Here are various ways to do that :

Alternatively, you can use a JsonDeserializer on either your whole class or one of its fields (the date). Examples in the link below



回答2:

List itemCreate a class to extend JsonDeserializer

public class CustomJsonDateDeserializer extends JsonDeserializer {     @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 on setter methods.

Thanks @Varun Achar answer, url



回答3:

You can use @DateTimeFormat

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!