开发者

Jackson serializationConfig

I am using Jackson JSON in a Spring 3 MVC app. To not serialize each and every single Date field, I created a custom objectmapper that uses a specific DateFormat:

@Component("jacksonObjectMapper")
public class CustomObjectMapper extends ObjectMapper
{
    Logger log = Logger.getLogger(CustomObjectMapper.class);

    @PostConstruct
    public vo开发者_开发百科id afterProps()
    {
        log.info("PostConstruct... RUNNING");
        //ISO 8601
        getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ"));


    }

    //constructors...

}

This custom ObjectMapper is injected into the JsonConverter:

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json" />
    <property name="objectMapper" ref="jacksonObjectMapper" /> <!-- defined in CustomObjectMapper -->
</bean>

There is no exception in the logs and serialization works, but it is not picking up the dateformat, it simple serializes to a timestamp. The @PostConstruct annotation works, the log statement in the method is in the logs.

Does anyone know why this fails?


You may also need to specify that you want textual Date serialization, by doing:

configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

(although I was assuming setting non-null date format might also trigger it, but maybe not)

Also, you can do configuration of mapper directly from constructor (which is safe). Not that it should change behavior, but would remove need for separate configuration method.


I've done the below which works to get around compatability with Java / PHP timestamps. Java uses milliseconds since EPOCH and PHP uses seconds so was simpler to use ISO dates.

I declare the below message adapters:

<bean id="messageAdapter"
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean id="jacksonJsonMessageConvertor"
                class="my.app.MyMappingJacksonHttpMessageConverter"/>                   
        </list>
    </property>
</bean>

And MyMappingJacksonHttpMessageConverter looks like the below:

public class MyMappingJacksonHttpMessageConverter extends MappingJacksonHttpMessageConverter {

public MyMappingJacksonHttpMessageConverter(){
    super();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    setObjectMapper(objectMapper);
}
}

With the above all dates are written out in ISO format.


For Spring config application.properties

spring.jackson.serialization.fail-on-empty-beans=false
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜