我正在製作一個帶有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「'。同樣的情況也反映在你得到的錯誤消息中。因此,設置傑克遜格式可以解析該格式。 –