How To format dates in Json within Spring 3

fievelk · August 5, 2013

After I managed to fix the Datatables jQuery plugin, finally squeezing my Movie class into the awesome table I prepared in my jsp, I found out that the dates in the columns were absolutely unintelligible: they were not properly formatted, and so they were showing up as a Long useless number.

My DataTables implementation uses Json to call the informations with which I’ll fill the table’s columns and rows. So, what I needed was something like a “real-time date formatter” for Json, something that would have been able to pick up my Date object from the model, format it in a comprehensible string format, and pass it to my DataTables plugin as Json.

If this is your situation at the moment, you’ll probabily find this guide useful, since it’s not very long and not very complicated. Well, it’s not complicated at all, actually.

I assume you’ve got a jsp (i.e. movielist.jsp), a controller class (i.e. MovieController.java) and a simple java class for the objects you want to manage in your Json call (e.g. Movie.java). Oh, you should also have enabled Spring annotation based configuration (see the reference links at the bottom of this post). So…

The steps!

  1. Create a DateJsonSerializer class that extends JsonSerializer. Like this:
     public class DateJsonSerializer extends JsonSerializer<date> {
    
         @Override
         public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
         throws IOException, JsonProcessingException {
             DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
           jgen.writeString(formatter.format(value));
         }
     }
    

    As you can see, the serialize method sets up the format you want to use for your date strings.

  2. In Movie.java class, insert the @JsonSerialize annotation above the date getters:

     @JsonSerialize(using=DateJsonSerializer.class)
     public Date getDate_in() {
         return date_in;
     }
     public void setDate_in(Date date_in) {
         this.date_in = date_in;
     }
    

That’s it. Yes, your work should already be done.

If you find something not working, please comment and I’ll try to figure out a proper solution.

References

Twitter, Facebook