Introduction to Jackson ObjectMapper
Jackson ObjectMapper
Introduction
In this blog post, we’ll explore the fundamentals of Jackson Object Mapper and delve into its practical usage.
What is Jackson Object Mapper?
Jackson is a high-performance JSON processor for Java, providing a set of tools to work with JSON data. At its core is the Jackson Object Mapper, a module that facilitates the conversion between Java objects and JSON data, as well as other data formats like XML. It is widely used in enterprise-level applications and open-source projects due to its simplicity, versatility, and robust performance.
Getting Started
To integrate Jackson into your project, you can include the Jackson dependencies in your build tool (e.g., Maven, Gradle). Once added, you can start using the ObjectMapper class to serialize Java objects to JSON and deserialize JSON back to Java objects.
Maven Dependency
1 | <properties> |
Serialization
use ObjectMapper.writeValueAsString(Object) method to convert Java object to JSON string. com.fasterxml.jackson.databind.ObjectMapper is the main class to perform serialization and deserialization in Jackson.
Entity
1 | public class Item { |
Convert Java object to JSON string
1 | ObjectMapper objectMapper = new ObjectMapper(); |
output:
1 | {"name":"book","price":20} |
Deserialization
use ObjectMapper.readValue(String, Class) method to convert JSON string to Java object.
1 | String jsonString = /* JSON string from some source */; |
Annotations for Customization:
Jackson provides a set of annotations that allow fine-grained control over the serialization and deserialization process. For example,
@JsonProperty
lets you specify the name of a property when serialized@JsonInclude
allows you to exclude null or empty values from the output@JsonPropertyOrder
lets you specify the order of properties in the output@JsonIgnore
excludes a property from serialization and deserialization@JsonManagedReference
and@JsonBackReference
manage bidirectional relationships
Example:
1 |
|
Sample output:
1 | { |
@JsonIgnoreProperties
- Annotation that can be used to either suppress serialization of properties (during serialization), or ignore processing of JSON properties read (during deserialization).
1 | Example: |
Handling Date Formats
Date serialization and deserialization often require specific formats. Jackson allows you to configure date formats globally or on a per-field basis:
1 | objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); |
Handling Java 8 Date/Time Types
With the introduction of Java 8, new date and time types like LocalDate
, LocalDateTime
, and ZonedDateTime
have become popular. Jackson provides a module called jackson-datatype-jsr310
to handle these types:
1 | <dependency> |
To use the module, you can register it with the ObjectMapper:
1 | ObjectMapper objectMapper = new ObjectMapper(); |
output
1 | { |
To serialize and deserialize Java 8 date/time types in a readable format, you can configure the ObjectMapper as follows:
1 | ObjectMapper objectMapper = new ObjectMapper(); |
SerializationFeature.WRITE_DATES_WITH_ZONE_ID: When enabled, the date/time values are serialized with the time zone ID, such as “Asia/Shanghai”.
DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE: When disabled, the date/time values are deserialized without adjusting to the context time zone. This is useful when you want to preserve the original time zone from the Json string.
Handling List
1 | ObjectMapper objectMapper = new ObjectMapper(); |
In this example, The TypeReference<List<Item>>(){}
is used to specify the type of the list.
If you just juse List.class
as the type, you will get a list of LinkedHashMap. and results in a ClassCastException when you try to cast it to List<Item>
.
Handling Polymorphic Types:
When working with polymorphic types, Jackson supports annotations like @JsonTypeInfo
and @JsonSubTypes
to handle the serialization and deserialization of class hierarchies:
1 |
|
Conclusion
Jackson Object Mapper simplifies the complex task of data serialization and deserialization in Java applications. Its flexibility, performance, and extensive features make it an essential tool for developers working with JSON and other data formats. By understanding the basics and exploring advanced features, developers can harness the full potential of Jackson to streamline data processing in their projects.