Spring @ResponseBody Jackson JsonSerializer with JodaTime Spring @ResponseBody Jackson JsonSerializer with JodaTime json json

Spring @ResponseBody Jackson JsonSerializer with JodaTime


Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:

<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" /><bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" ></bean>

For CustomObjectMapper:

public class CustomObjectMapper extends ObjectMapper {    public CustomObjectMapper() {        super();        configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);        setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));    }}

Of course, SimpleDateFormat can use any format you need.


@Moesio pretty much got it. Here's my config:

<!-- Configures the @Controller programming model --><mvc:annotation-driven/><!-- Instantiation of the Default serializer in order to configure it --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterConfigurer" init-method="init">    <property name="messageConverters">        <list>            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">                <property name="objectMapper" ref="jacksonObjectMapper" />            </bean>        </list>    </property></bean><bean id="jacksonObjectMapper" class="My Custom ObjectMapper"/><bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />

The bit that got me is that <mvc:annotation-driven/> makes its own AnnotationMethodHandler and ignores the one you make manually. I got the BeanPostProcessing idea from http://scottfrederick.blogspot.com/2011/03/customizing-spring-3-mvcannotation.html to configure the one that gets used, and voilĂ ! Works like a charm.


Same using JavaConfig of Spring 3:

@Configuration@ComponentScan()@EnableWebMvcpublic class WebConfig extends WebMvcConfigurerAdapter{    @Override    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters)    {        converters.add(0, jsonConverter());    }    @Bean    public MappingJacksonHttpMessageConverter jsonConverter()    {        final MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();        converter.setObjectMapper(new CustomObjectMapper());        return converter;    }}