I'm working on a REST API in Spring MVC 3.2RC1.
I'm fetching a JPA entity with a org.joda.time.DateTime timestamp in it and let Spring serialise it into JSON using
@RequestMapping(value = "/foobar", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
Using the default Jackson2 settings in Spring as I've only added
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.1</version>
</dependency>
to my POM and let Spring wire it up itself.
The controller is generating:
"created":{"year":2012,"dayOfMonth":30,"dayOfWeek":5,"era":1,"dayOfYear":335,"weekOfWeekyear":48,"weekyear":2012,"monthOfYear":11,"yearOfEra":2012,"yearOfCentury":12,"centuryOfEra":20,"millisOfSecond":39,"millisOfDay":52684039,"secondOfMinute":4,"secondOfDay":52684,"minuteOfHour":38,"minuteOfDay":878,"hourOfDay":14,"millis":1354282684039,"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Europe/Stockholm"},"fixed":false,"id":"Europe/Stockholm"},"chronology":{"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Europe/Stockholm"},"fixed":false,"id":"Europe/Stockholm"}},"afterNow":false,"beforeNow":true,"equalNow":false}
But I would like it to be and ISO8601 date such as 2007-11-16T20:14:06.3Z (or with the offset).
My guess is that I need to access the ObjectMapper and set mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); But how do I get access to the ObjectMapper when using
<mvc:annotation-driven />
P.S. I'm persisting the objects to PostgreSQL with JPA/Hibernate4 using UserType to get JodaTime support. D.S.
Update
The config below solves it for java.util.Date but still no dice for JodaTime.
<annotation-driven>
<message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper">
<beans:bean
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true" p:simpleDateFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ">
</beans:bean>
</beans:property>
</beans:bean>
</message-converters>
</annotation-driven>
See Question&Answers more detail:
os