Jackson and JSON in Java, finally learn with a coding-first approach:
>> Download the eBookMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
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.
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.
