I think I must be misunderstanding how Zones work in java's ZonedDateTime class. When I use Jackson to serialize and then deserialize now(), the deserialized value has getZone() == "UTC" instead of the "Z" in the serialized value. Can anyone explain to me why this is and what I should be doing instead?
The code below prints:
{"t":"2017-11-24T18:00:08.425Z"}
Data [t=2017-11-24T18:00:08.425Z]
Data [t=2017-11-24T18:00:08.425Z[UTC]]
Z
UTC
The java source:
<!-- language: java -->
package model;
import static org.junit.Assert.*;
import java.io.IOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class ZonedDateTimeSerializationTest {
static public class Data {
@Override
public String toString() {
return "Data [t=" + t + "]";
}
public ZonedDateTime getT() {
return t;
}
public void setT(ZonedDateTime t) {
this.t = t;
}
ZonedDateTime t = ZonedDateTime.now(ZoneOffset.UTC);
};
@Test
public void testDeSer() throws IOException {
Data d = new Data();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
String serialized = objectMapper.writer()
.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.writeValueAsString(d);
System.out.println(serialized);
Data d2 = objectMapper.readValue(serialized, Data.class);
System.out.println(d);
System.out.println(d2);
System.out.println(d.getT().getZone());
System.out.println(d2.getT().getZone());
// this fails
assertEquals(d, d2);
}
}
By default, during deserialization of a ZonedDateTime
, Jackson will adjust the parsed timezone to the contextually provided one. You can modify this behavior with this setting so that the parsed ZonedDateTime
will stay at Z
:
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
More details here
I did this to actually preserve the timezones:
mapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID)
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With