Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (de)serialize DateTime objects as ISO8601 using Jackson 2.0?

Tags:

java

jackson

I'd like to know whether it is possible to [de]serialize a Joda DateTime object into a ISO8601 String using Jackson without creating a custom JsonSerializer<DateTime>.

Surely this is a common enough function that is built into the library somewhere? The closest I could find is a SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, but this seems to only apply to Date objects.

EDIT:

I found this class: ISO8601DateFormat, but when I try the following code I don't get an ISO8601 string:

ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new ISO8601DateFormat());
mapper.writer().writeValueAsString(DateTime.now());

Looks like Jackson doesn't treat Date and DateTime objects equally.

UPDATE:

I ended up writing a custom serializer for ISO8601 DateTime strings.

like image 711
jabalsad Avatar asked Dec 01 '25 02:12

jabalsad


1 Answers

I haven't tried it myself, but it looks like you should be able to do this:

// Set the date format to the desired (in this case, ISO8601)
objectMapper.getDeserializationConfig().setDateFormat(myDateFormat);

// or, as of Jackson 1.8, use
ObjectMapper#withDateFormat(myDateFormat)

since

Starting with version 1.4, Jackson offers some support for Joda Time data types: basically, its DateTime can be automatically serialized/deserialized similar to how java.util.Date is handled.

The current API call is:

.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
like image 144
Matt Ball Avatar answered Dec 03 '25 16:12

Matt Ball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!