Jun 282013
 

Here is how to customize how Jackson serializes Joda-Time dates to JSON:

objectMapperFactory.registerModule(new SimpleModule() {
    {
        addSerializer(DateTime.class, new StdSerializer<DateTime>(DateTime.class) {
            @Override
            public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
                 jgen.writeString(ISODateTimeFormat.date().print(value));
            }
        });
    }
});

You can use this in combination with JodaModule, just place it after the JodaModule is registered.

Alternatively, if all you need is to write DateTimes in ISO 8061 format instead of as Unix epochs, you can use the following:

objectMapperFactory.registerModule(new JodaModule())
objectMapperFactory.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

JodaModule registers a custom DateTimeSerializer that takes the setting into account. However, unlike the standard Java Date implementation, SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS and getSerializationConfig().setDateFormat(myDateFormat) are ignored, so there is no way to fine-tune the serialization.

Ultimately a more elegant solution would be to give JodaModule some additional constructors or setters that allow passing in a DateFormatter that its various helper classes would use.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)