我正在制作一个带有Angular2前端的REST API。在我的Spring jackson配置中,我设置了这个spring.jackson.date-format=EEE MMM dd yyyy HH:mm:ss zzz (zzzz),因为我使用bootstrap-datepicker插件输出的日期格式如下:Wed May 31 2017 00:00:00 GMT+0200 (W. Europe Daylight Time)。当我尝试将日期提交到一个具有此变量的DTO时,即private Date defaultDatetime;,REST API返回400错误请求。
{"timestamp":"mer. mai 03 2017 14:16:47",
"status":400,
"error":"Bad Request",
"exception":"org.springframework.http.converter.HttpMessageNotReadableException",
"message":"Could not read document: Can not construct instance of java.util.Date from String value '2017-05-01T22:00:00.000Z': not a valid representation (error: Failed to parse Date value '2017-05-01T22:00:00.000Z': Unparseable date: \"2017-05-01T22:00:00.000Z\")\n at [Source: java.io.PushbackInputStream@77b19daf; line: 1, column: 68] (through reference chain: ch.heigvd.form.api.dto.FormDTO[\"fields\"]->java.util.ArrayList[0]->ch.heigvd.form.api.dto.field.DateFieldDTO[\"defaultDate\"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2017-05-01T22:00:00.000Z': not a valid representation (error: Failed to parse Date value '2017-05-01T22:00:00.000Z': Unparseable date: \"2017-05-01T22:00:00.000Z\")\n at [Source: java.io.PushbackInputStream@77b19daf; line: 1, column: 68] (through reference chain: ch.heigvd.form.api.dto.FormDTO[\"fields\"]->java.util.ArrayList[0]->ch.heigvd.form.api.dto.field.DateFieldDTO[\"defaultDate\"])",
"path":"/api/forms"}
你有什么想法关于jackson反序列化时应该输入哪种日期格式?或者我应该直接在前端更改格式?
更新
我通过自定义序列化器使其工作。这是属性文件中的配置:
spring.jackson.date-format=ch.heigvd.form.configuration.CustomJsonDateDeserializer spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
以下是序列化器:
public class CustomJsonDateDeserializer extends ISO8601DateFormat {
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
toAppendTo.append(format.format(date));
return toAppendTo;
}
@Override
public Date parse(String source, ParsePosition pos) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
return format.parse(source);
} catch (ParseException var4) {
return null;
}
}
}
Date()
对象。当您进行后端请求时,它会使JSON.stringify(date)
,该字符串返回为"2017-05-03T15:07:34.056Z"
。同样的内容反映在您收到的错误消息中。因此,请设置Jackson格式以能够解析该格式。 - A. Tim