Created
January 10, 2025 15:24
-
-
Save asgeirn/81bb2f246960c0a3242c694d45cdf3e0 to your computer and use it in GitHub Desktop.
Jackson Dates with Time Zones
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.wildfly.quickstarts.helloworld; | |
import com.fasterxml.jackson.databind.DeserializationFeature; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.databind.SerializationFeature; | |
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; | |
import org.junit.Test; | |
import java.io.IOException; | |
import java.time.ZoneId; | |
import java.time.ZonedDateTime; | |
import static junit.framework.TestCase.assertEquals; | |
/* You need the following dependency: | |
<dependency> | |
<groupId>com.fasterxml.jackson.datatype</groupId> | |
<artifactId>jackson-datatype-jsr310</artifactId> | |
</dependency> | |
*/ | |
public class JacksonDatesWithTimeZones { | |
@Test | |
public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect() | |
throws IOException { | |
ObjectMapper objectMapper = new ObjectMapper(); | |
objectMapper.registerModule(new JavaTimeModule()); | |
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); | |
objectMapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID); | |
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); | |
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); | |
String converted = objectMapper.writeValueAsString(now); | |
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); | |
System.out.println("input: " + now); | |
System.out.println("serialized: " + converted); | |
System.out.println("restored: " + restored); | |
assertEquals(now, restored); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment