Serializing Date With Jackson

When serializing java.util.Date, Jackson gets the long time value by calling getTime() and outputs the time. For example a class:

public class Customer {
    private String id;
    private Date birthDay;
    //Getter and setter...

May be serialized as:

{"id":"1", "birthDay":1320987600000}

Working with date like this may be difficult for certain clients. How will you output formatted date, like “11-11-2011”? Most tutorials on the web, such as this one, recommend writing a custom serializer. A simpler approach is to provider a getter method that does the formatting. For example:

public String getBirthdayFormatted() {
   SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");

   return sdf.format(birthDay);

Now, the JSON will look like this:

{"id":"1", "birthDay":1320987600000, "birthdayFormatted":"11-11-2011"}

You can apply the same principle for formatting of currency, time or anything else. This approach, aside from its simplicity, has two added benefits:

  • The code is not using any Jackson specific solution.
  • We are outputting both the raw and the formatted values. Advanced clients can do their own formatting using the raw value.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s