Date format in the json output using spring boot

Pramod picture Pramod · Mar 13, 2015 · Viewed 103k times · Source

I am working on spring boot for creating a REST application. And I have a DTO as shown below:

public class Subject {

private String uid;
private String number;
private String initials;
private Date dateOfBirth;

And I use Spring-Hateos and the reurn type of my controller is ResponseEntity<Resources<Resource<Subject>>>. I need the date to be displayed in the "yyyy-mm-dd" format.

Answer

Yagnesh Agola picture Yagnesh Agola · Mar 13, 2015

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

For Example :

public class Subject {

     private String uid;
     private String number;
     private String initials;

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date dateOfBirth;  

     //Other Code  

}  

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.