无法在spring中通过requestBody将String转换为Date [英] Unable to convert String to Date by requestBody in spring
问题描述
我有以下代码:
DTO:
Class MyDTO {
import java.util.Date;
private Date dateOfBirth;
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
控制器
public void saveDOB(@RequestBody MyDTO myDTO,HttpServletRequest httprequest,HttpServletResponse httpResponse) {
System.out.println("Inside Controller");
System.out.println(myDTO.getDateOfBirth());
System.out.println(myDTO.getDateOfBirth());
}
JSON要求:
{
"dateOfBirth":"2014-09-04",
}
如果我发送请求为yyyy-mm-dd自动转换为日期对象发生。
控制器中的输出: -
dateOfBirth = Thu Sep 04 05:30:00 IST 2014
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
但是当我以dd-mm-yyyy格式发送DateofBirth时它不会自动将String转换为Date。所以我怎么能处理这种情况。
JSON请求:
{
"dateOfBirth":"04-09-2014",
}
输出:没有控制台中的输出甚至没有到达控制器。
Output: No Output in console does not even reaches controller.
我尝试使用@DateTimeFormat,但它没有工作。
I have tried with @DateTimeFormat but its not working.
我使用的是Spring 4.02请su ggest是否有我们可以使用的注释。
I am using Spring 4.02 Please suggest is there any annotation we can use.
推荐答案
@DateTimeFormat
是用于表单支持(命令)对象。您的JSON由Spring的 MappingJackson2HttpMessageConverter
中的杰克逊 ObjectMapper
处理(默认情况下)(假设最新版本的Jackson)。这个 ObjectMapper
有许多可以处理的默认日期格式。似乎 yyyy-mm-dd
就是其中之一,但 dd-mm-yyyy
不是。
@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.
您需要使用 ObjectMapper
注册自己的日期格式并注册 ObjectMapper
使用 MappingJackson2HttpMessageConverter
。以下是各种方法:
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 :
- Configuring ObjectMapper in Spring
- Spring, Jackson and Customization (e.g. CustomDeserializer)
或者,您可以使用 JsonDeserializer
在您的整个班级或其中一个字段(日期)上。以下链接中的示例
Alternatively, you can use a JsonDeserializer
on either your whole class or one of its fields (the date). Examples in the link below
- Right way to write JSON deserializer in Spring or extend it
- How to deserialize JS date using Jackson?
这篇关于无法在spring中通过requestBody将String转换为Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!