【问题标题】:The request sent by the client was syntactically incorrect using @DateTimeFormat使用@DateTimeFormat 客户端发送的请求在语法上不正确
【发布时间】:2013-11-22 17:13:23
【问题描述】:

我有一个 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. 删除 test,一切正常并按预期工作。

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

【问题讨论】:

    标签: java mysql json spring hibernate


    【解决方案1】:

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

    如果您将 url 编码的表单参数与 @ModelAttribute 一起使用,则可以使用 @DateTimeFormat。 Spring 注册了一些转换器,这些转换器可以将请求参数中的字符串值转换为Date 对象。 This is described in the deocumentation.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2019-02-20
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多