我正在制作一个带有Angular2前端的REST API。在我的杰克逊Spring配置中,我设置了这个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错误的请求错误。Angular2 Spring引用日期序列化
{"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: [email protected]; 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: [email protected]; 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 deserializatrion?还是应该直接在前端更改格式?
更新
我得到了它与自定义序列化工作。这是属性文件中的配置。
spring.jackson.date格式= ch.heigvd.form.configuration.CustomJsonDateDeserializer spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS =假
这是串行:
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;
}
}
}
我很确定boostrsrap-datepicker返回js Date()对象。当你创建后端请求时,它会生成'JSON.stringify(date)',它返回字符串为“”2017-05-03T15:07:34.056Z“'。同样的情况也反映在你得到的错误消息中。因此,设置杰克逊格式可以解析该格式。 –