1

我有一个 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 -> date),我这样注释 POJO:

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

所以test应该格式化为月/年。但是我用 Firefox RESTClient 尝试过,我总是得到 The request sent by the client was syntactically incorrect.Removing test,一切都很好并且按预期工作。

看来,这有@DateTimeFormat(pattern = "MM/yy")什么问题吗?

4

1 回答 1

5

因为您使用RequestBody的是application/json内容类型,所以 Spring 将使用它MappingJackson2HttpMessageConverter来将您的 JSON 转换为您的类型的对象。但是,您提供的日期字符串11/14与任何预配置的日期模式都不匹配,因此无法正确解析。,MappingJackson2HttpMessageConverter或者更具体地说,做这项工作的,对 Spring 注释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;

如果您将@DateTimeFormaturl 编码的表单参数与@ModelAttribute. Spring 注册了一些转换器,这些转换器可以将字符串值从请求参数转换为Date对象。这在 deocumentation 中有描述。

于 2013-11-11T02:13:54.377 回答