Maciej Papie┼╝ Maciej Papie┼╝ - 28 days ago 12
Java Question

How to preserve the offset while deserializing OffsetDateTime with Jackson

In an incoming JSON, I have an ISO8601-compliant datetime field, containing zone offset. I'd like to preserve this offset, but unfortunately Jackson defaults to GMT/UTC while deserializing this field (what I understood from http://wiki.fasterxml.com/JacksonFAQDateHandling).

@RunWith(JUnit4.class)
public class JacksonOffsetDateTimeTest {

private ObjectMapper objectMapper;

@Before
public void init() {
objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(new JavaTimeModule())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}

@Test
public void test() throws IOException {
final String json = "{ \"date\": \"2000-01-01T12:00:00.000-04:00\" }";
final JsonType instance = objectMapper.readValue(json, JsonType.class);

assertEquals(ZoneOffset.ofHours(-4), instance.getDate().getOffset());
}
}


public class JsonType {
private OffsetDateTime date;

// getter, setter
}


What I'm getting here is:

java.lang.AssertionError: expected:<-04:00> but was:<Z>


How can I make the returned OffsetDateTime to contain the original Offset?

I'm on Jackson 2.8.3.

Answer

Change your Object Mapper to this to disable the ADJUST_DATES_TO_CONTEXT_TIME_ZONE.

objectMapper = Jackson2ObjectMapperBuilder.json()
            .modules(new JavaTimeModule())
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
            .build();