Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
Maciej Papież Avatar asked Nov 08 '16 13:11

Maciej Papież


1 Answers

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();
like image 66
s7vr Avatar answered Oct 07 '22 17:10

s7vr