I'm making a REST API with an Angular2 frontend. In my Spring configuration for jackson I have set this spring.jackson.date-format=EEE MMM dd yyyy HH:mm:ss zzz (zzzz) because I use the bootstrap-datepicker plugin which outputs dates like this: Wed May 31 2017 00:00:00 GMT+0200 (W. Europe Daylight Time).
When I try to post a date to a DTO which has variables like this one private Date defaultDatetime; The REST API returns a 400 Bad request error.
{"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"}
Any idea what kind of date-format I should put for jackson deserializatrion? Or should I change the format directly in the frontend?
Update
I got it working with a custom serializer. This is the configuration in the properties file.
spring.jackson.date-format=ch.heigvd.form.configuration.CustomJsonDateDeserializer spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
This is the serializer:
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()object. When you make backend request it makesJSON.stringify(date), that returns string as"2017-05-03T15:07:34.056Z". Same is reflected in error message that you got. So set Jackson format to be able to parse that format.