Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson ObjectMapper adjusts dates to context timezone when deserializing even if explicitly disabled

This is the format of the date in JSON that I want to serialize/deserialize:

"2014-06-18T06:26:56-07:00"

The Joda DateTime field is declared as follows:

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ")
    private DateTime dueTime;

The mapper:

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
            .registerModule(new JodaModule())
            .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

mapper.writeValueAsString(objectWithDT)).as("application/json")

In the resulting JSON the date with timezone above changes to:

2014-06-18T13:26:56+0000
like image 352
Aydin Avatar asked Aug 03 '16 21:08

Aydin


1 Answers

DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE is a deserialization feature and it's not taken into consideration when performing a serialization.

One possible solution is to create an ObjectMapper instance with a TimeZone:

ObjectMapper mapper =  new ObjectMapper()
            .enable(SerializationFeature.INDENT_OUTPUT)
            .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
            .registerModule(new JodaModule())
            .setTimeZone(TimeZone.getTimeZone("GMT-7"));

For more details, check the DateTimeSerializer code.

like image 141
cassiomolin Avatar answered Oct 27 '22 14:10

cassiomolin