Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll explore how to serialize OffsetDateTime with Jackson.

OffsetDateTime is an immutable representation of date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system. For example, 2023-10-31T01:30+01:00 represents the date-time of the last minute of October 31st, 2023, with an offset of one hour from UTC.

Jackson, by default, doesn’t serialize OffsetDateTime because it’s a Java 8 date-time type. Let’s see how we can enable it.

2. Project Setup

Let’s start with a simple example. We’ll create a class with a field of type OffsetDateTime and serialize it to JSON.

2.1. Dependency

Let’s start by adding the Jackson databind dependency to our pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.1</version>
</dependency>

2.2. Code Example

First, let’s define the class that we want to serialize:

public class User {
    private OffsetDateTime createdAt;

    // constructors, getters and setters
}

Next, we’ll create a method to serialize a User object to JSON:

String serializeUser() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    User user = new User();
    user.setCreatedAt(OffsetDateTime.parse("2021-09-30T15:30:00+01:00"));

    return objectMapper.writeValueAsString(user);
}

If we call the above method, we’ll get the below error:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.OffsetDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.baeldung.offsetdatetime.User["createdAt"])

As we can see, Jackson doesn’t support serializing OffsetDateTime by default. Let’s look at ways to fix this.

3. Registering JavaTimeModule

As suggested by the error message, Jackson provides a module called JavaTimeModule that we can use to serialize OffsetDateTime in the correct format.

First, we need to include the jackson-datatype-jsr310 dependency in our pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.14.1</version>
</dependency>

Now, we can register this module with the ObjectMapper before serializing the object:

String serializeUser() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.registerModule(new JavaTimeModule());
    
    User user = new User();
    user.setCreatedAt(OffsetDateTime.parse("2021-09-30T15:30:00+01:00"));

    return objectMapper.writeValueAsString(user);
}

We registered the JavaTimeModule with the ObjectMapper using the registerModule() method. We also disabled the SerializationFeature.WRITE_DATES_AS_TIMESTAMPS feature to get the date in the same format as the input and not as a timestamp.

When we call the method again, the error is gone, and we get the serialized date in the output. We can test this using a JUnit test:

@Test
void givenUser_whenSerialized_thenCreatedDateIsSerialized() throws JsonProcessingException {
    Assertions.assertEquals("{\"createdAt\":\"2021-09-30T15:30:00+01:00\"}", Main.serializeUser());
}

4. Custom Serialization and Deserialization

Another way to fix the issue is to create a custom serializer for OffsetDateTime. This would be the preferred way if we also want to customize the format of the date.

4.1. Custom Serializer

We can do this by creating a class that extends the JsonSerializer class of Jackson and overriding the serialize() method:

public class OffsetDateTimeSerializer extends JsonSerializer<OffsetDateTime> {
    private static final DateTimeFormatter DATE_TIME_FORMATTER
      = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss XXX");
    
    @Override
    public void serialize(OffsetDateTime value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) 
      throws IOException {
        if (value == null) {
            throw new IOException("OffsetDateTime argument is null.");
        }
        jsonGenerator.writeString(DATE_TIME_FORMATTER.format(value));
    }
}

Let’s look at some important points about the code above:

  • We created a DateTimeFormatter with the format we want to use. Here we have used a different format than the default one.
  • Next, we formatted the date by calling the format() method on the DateTimeFormatter.
  • Finally, we wrote the formatted date to the JsonGenerator by calling the writeString() method.

Now we can register this serializer with the ObjectMapper before serializing the object:

String customSerialize() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new SimpleModule().addSerializer(OffsetDateTime.class, new OffsetDateTimeSerializer()));
    
    User user = new User();
    user.setCreatedAt(OffsetDateTime.parse("2021-09-30T15:30:00+01:00"));
    
    return objectMapper.writeValueAsString(user);
}

We can now test that we get the date in the format specified in the serializer:

@Test
void givenUser_whenCustomSerialized_thenCreatedDateIsSerialized() throws JsonProcessingException {
    Assertions.assertEquals("{\"createdAt\":\"30-09-2021 15:30:00 +01:00\"}", Main.customSerialize());
}

4.2. Custom Deserializer

Since we have created a custom serializer, we also need to create a custom deserializer to deserialize the date from the JSON string. If we don’t do this, we get the same InvalidDefinitionException again.

We can do this by creating a class that extends JsonDeserializer and overriding the deserialize() method:

public class OffsetDateTimeDeserializer extends JsonDeserializer<OffsetDateTime> {
    private static final DateTimeFormatter DATE_TIME_FORMATTER
      = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss XXX");
    
    @Override
    public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) 
      throws IOException {
        String dateAsString = jsonParser.getText();
        if (dateAsString == null) {
            throw new IOException("OffsetDateTime argument is null.");
        }
        return OffsetDateTime.parse(dateAsString, DATE_TIME_FORMATTER);
    }
}

Similar to the serializer, we created a DateTimeFormatter with the format we want to use. In the end, we passed the formatter to the parse() method to get the OffsetDateTime object to return the value.

We can register this deserializer with the ObjectMapper wherever we want to deserialize the object:

String customDeserialize() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new SimpleModule().addDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializer()));
    
    String json = "{\"createdAt\":\"30-09-2021 15:30:00 +01:00\"}";
    User user = objectMapper.readValue(json, User.class);
    
    return returnedUser.getCreatedAt().toString();
}

We get the date in the default OffsetDateTime format in the output:

@Test
void givenUser_whenCustomDeserialized_thenCreatedDateIsDeserialized() throws JsonProcessingException {
    Assertions.assertEquals("2021-09-30T15:30+01:00", Main.customDeserialize());
}

5. Conclusion

In this article, we saw how to serialize and deserialize OffsetDateTime with Jackson. We saw two solutions to fix the default serialization of OffsetDateTime with Jackson – first using the JavaTimeModule and second by defining a custom serializer.

As usual, the code examples in this article can be found over on GitHub.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Jackson (eBook) (cat=Jackson)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.