I know it's an old question but I answer because I had the same problem today and I lost 4 hours of work to find the solution. The problem here is spring uses Jackson to serialize and deserialize JSON. @DateTimeFormat
annotation will not do the job, you have to tell Jackson how to serialize the date. You have two solutions: the first one is the simplier and is to use @JsonFormat
annotation in the getter method:
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy")
public Date getDob(){
return dob;
}
The second solution is to create a custom serializer for date fields like this:
public class JsonDateSerializer extends JsonSerializer<Date>{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
and then use the annotation in the get method:
@JsonSerialize(using=JsonDateSerializer.class)
public Date getDob(){
return dob;
}
this link explains how to do the serializer
https://dzone.com/articles/how-serialize-javautildate
I faced another problem, I was importing in my JsonDateSerializer class the classes from org.codehaus.jackson
package, but Spring gived me this error:
java.io.FileNotFoundException: class path resource [org/codehaus/jackson/map/JsonSerializer.class] cannot be opened because it does not exist
So I changed all the imports to the package
com.fasterxml.jackson
and it all works fine.
I hope it can help someone.