could not read JSON: Can not construct instance of java.util.Date from String
value \'2012-07-21 12:11:12\': not a valid representation(\"yyyy-MM-dd\'T\'HH:mm:ss.SS
Yet another way is to have a custom Date object which takes care of its own serialization.
While I don't really think extending simple objects like Date
, Long
, etc. is a good practice, in this particular case it makes the code easily readable, has a single point where the format is defined and is rather more than less compatible with normal Date
object.
public class CustomFormatDate extends Date {
private DateFormat myDateFormat = ...; // your date format
public CustomFormatDate() {
super();
}
public CustomFormatDate(long date) {
super(date);
}
public CustomFormatDate(Date date) {
super(date.getTime());
}
@JsonCreator
public static CustomFormatDate forValue(String value) {
try {
return new CustomFormatDate(myDateFormat.parse(value));
} catch (ParseException e) {
return null;
}
}
@JsonValue
public String toValue() {
return myDateFormat.format(this);
}
@Override
public String toString() {
return toValue();
}
}