使用@DateTimeFormat,客户端发送的请求在语法上是不正确的

时间:2013-11-11 00:54:50

标签: java mysql json spring hibernate

我有一个JSON格式的字符串,我用HTTP-PUT发送到带有Spring MVC和Hibernate的服务器。

Controller

@RequestMapping(value = "/", method = RequestMethod.PUT)
public ResponseEntity<Map<String, Object>> myTest(
        @RequestHeader("a") String a,
        @RequestBody MyTestClass b) { … }

JSON

{
 "number":"123",
 "test":"11/14"
}

test是java.util.Date(MySQL - &gt; date),我注释了这样的POJO:

@Column(name = "TEST")
@DateTimeFormat(pattern = "MM/yy")
private Date test;

因此test应格式化为月/年。但我尝试使用Firefox RESTClient,我总是得到它 The request sent by the client was syntactically incorrect.正在删除test,一切正常并按预期工作。

所以看来,@DateTimeFormat(pattern = "MM/yy")有问题吗?

1 个答案:

答案 0 :(得分:5)

由于您使用的RequestBody内容类型为application/json,因此Spring会使用其MappingJackson2HttpMessageConverter将您的JSON转换为您的类型的对象。但是,您提供的日期字符串11/14与任何预配置的日期模式都不匹配,因此无法正确解析它。 MappingJackson2HttpMessageConverter,或更具体地说,ObjectMapper执行此任务,对{注释@DateTimeFormat没有任何了解。

您需要告诉杰克逊您想要使用哪种日期模式。您可以使用自定义日期反序列化器

执行此操作
public class CustomDateDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        SimpleDateFormat format = new SimpleDateFormat("MM/yy");
        String date = jp.getText();

        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new JsonParseException(e);
        }
    }
}

然后简单地注释你的领域,以便杰克逊知道如何反序列化它。

@JsonDeserialize(using = CustomDateDeserializer.class)
private Date test;

如果您使用带有@DateTimeFormat的网址编码表单参数,则可以使用@ModelAttribute。 Spring注册了一些可以将String值从请求参数转换为Date对象的转换器。 This is described in the deocumentation.

相关问题