Home > English, java, javascript, work > Return usable Joda dates in JSON with Jackson

Return usable Joda dates in JSON with Jackson

Every sane person ditches the Java Date-api and uses Joda. Okay, sometimes you run into trouble. This time when I was using the Spring @ResponseBody to return JSON and my date got returned as a big hairy monster (some Chronology and things which really scared me).
In this short article I’ll explain how to fix it. Since I try to be concise please feel free to ask me to elaborate.

Since Spring sometimes seems to bundle an older version of Jackson I will include my Jackson-dependency to the dependencies:

<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.1.2</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.datatype</groupId>
 <artifactId>jackson-datatype-joda</artifactId>
 <version>2.1.2</version>
</dependency>

The important dependency is the last one. This gives you the class JodaModule, which does all the magic for you.

Now you have to create an ObjectMapper:

public class JodaObjectMapper extends ObjectMapper {

    public JodaObjectMapper() {
        super();
        registerModule(new JodaModule());
    }
}

Now add to *-web-servlet.xml:

<mvc:annotation-driven>
 <mvc:message-converters register-defaults="true">
 <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
 <property name="objectMapper">
 <bean class="net.jvw.JodaObjectMapper"/>
 </property>
 </bean>
 </mvc:message-converters>
</mvc:annotation-driven>

Now you’re almost done. In JSON the date will be returned as an array: [2011,10,5]

With new Date(array[0], array[1], array[2]) you will have a Date object in Javascript.

Categories: English, java, javascript, work
  1. No comments yet.
  1. No trackbacks yet.

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 )

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

%d bloggers like this: