Spring MVC Rest Services: Force Jackson to serialize dates as ISO-8601 dates

We’re creating a restful api for our Order Management Service at Backcountry.com.  One of the problems we came up against was that Jackson serializes dates as epochs by default instead of the standard ISO-8601 format.

As a side note… Jackson is a library that when put on the classpath of a Spring MVC project, spring automatically uses it to serialize the body of responses to JSON.  For more details about that see here: http://blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/

This stackoverflow question summarizes the problem well: http://stackoverflow.com/questions/7672211/java-spring-jackons-date-serialization/14490816#14490816

Through a variety of sources I pieced together what I think is a good solution.  (Which you can upvote on stackoverflow.)

The key to the solution is a new feature in Spring 3.1 where you can now customize the <mvc:annotation-driven> element.  See here for more details about that: http://blog.springsource.org/2011/02/21/spring-3-1-m1-mvc-namespace-enhancements-and-configuration/

Here’s my solution:

public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);            
        setDateFormat(new ISO8601DateFormat());

What this code does…

Line 1: Extend ObjectMapper

Line 3: Tell Jackson to stop sending dates as timestamps (instead it will send dates as strings.)

Line 4: Sets the date format of the dates that are now sent as strings.  (Note I also used Jackson’s built in convenience class ISO8601DateFormat, which automatically gives you ISO-8601 compliant dates.)

        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="customObjectMapper"/>

<bean id="customObjectMapper" class="CustomObjectMapper"/></code></pre>

What this code does… registers our CustomObjectMapper above as a spring bean.  Then uses that bean in the objectMapper property of the MappingJacksonHttpMessageConverter.  This basically tells Jackson to use this mapper for serialization instead of the default ObjectMapper.

Does this should give you nice dates like this: “2013-01-25T18:20:01-07:00” in your json responses.


Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s