Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.17.2</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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW