Introduction
Jackson is a widely used Java library for processing JSON data. It provides easy-to-use APIs for serializing Java objects to JSON and deserializing JSON into Java objects. Jackson is popular due to its high performance, flexible configuration, and powerful data-binding features.
What is Jackson?
Jackson is a high-performance JSON processor for Java. It helps convert Java objects to JSON and vice versa. The core class is ObjectMapper
, and it also provides useful annotations for customization.
Why Use Jackson?
- Simple API
- Fast and efficient
- Handles complex data structures
- Supports annotations for custom mapping
- Flexible configuration
1. Adding Jackson Dependency
Maven
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
Gradle
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
After importing Jackson, we can use the ObjectMapper class to perform marshalling (serialization) and unmarshalling (deserialization) of JSON data.
The ObjectMapper
class is the core of Jackson’s functionality. It provides methods to:
writeValueAsString(Object obj)
→ Serialize Java object to JSON string.writeValue(File resultFile, Object obj)
→ Serialize and write JSON directly to file.readValue(String json, Class<T> valueType)
→ Deserialize JSON string to Java object.readTree(String json)
→ Parse JSON into a tree ofJsonNode
.
2. Serialization (Marshalling)
What is Serialization?
Serialization is the process of converting a Java object into a format (in this case, JSON) that can be easily stored or transmitted, and later reconstructed back into the original object. In the context of Jackson, serialization is also known as marshalling.
When working with APIs, databases, or file storage, JSON is commonly used to represent structured data in a lightweight and human-readable format. Jackson’s ObjectMapper
makes this conversion simple and efficient.
2.1 Serialization Java Object to JSON
✔️ Example User.java Class
public class User {
private String name;
private int age;
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
✔️ Serialization Example
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonSerializationExample {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();//Create an instance of ObjectMapper
User user = new User("Ashish Kumar", 30);
String jsonString = objectMapper.writeValueAsString(user);//Serialize the Object to JSON String
System.out.println("Serialized JSON: " + jsonString);
}
}
➔ Output:
{"name":"Ashish Kumar","age":30}
2.2 Writing JSON to a File
⚡ Instead of working only with strings, Jackson allows you to directly write JSON into files using:
✔️ Example
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
public class JacksonWriteToFileExample {
public static void main(String[] args) {
try {
// Create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
// Create a User object
User user = new User("Ashish Kumar", 30);
// Write the User object as JSON to the file "user.json"
objectMapper.writeValue(new File("user.json"), user);
System.out.println("JSON file has been written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
➔Output : Resulting File Content (user.json):
{"name":"Ashish Kumar","age":30}
👉This approach is helpful when persisting data or creating configuration files.
✅ Why Is This Useful?
- Data Transmission: Serialized JSON is easy to send over HTTP in REST APIs.
- Data Storage: Persist objects in a JSON file for later retrieval.
- Logging and Debugging: Easily log object states in a readable format.
- Configuration Files: Store application settings in JSON.
3. Deserialization (Unmarshalling)
What is Deserialization?
Deserialization is the process of converting JSON data into a Java object. In the context of Jackson, this process is often called unmarshalling. It allows us to take a structured JSON string (or file) and transform it into a corresponding Java object so that we can easily work with the data in a type-safe manner.
✅ Why Is Deserialization Important?
- Reading API Responses: When calling REST APIs, the response is often in JSON format. To work with the data in Java, we deserialize it into objects.
- Reading Configuration Files: JSON configuration files are commonly used for application settings.
- Data Persistence: Deserialize stored JSON files back into Java objects for processing or display.
✅ How Does Jackson Perform Deserialization?
Once Jackson is imported and the ObjectMapper
is available, we use it to convert JSON strings or files into Java objects.
3.1 Deserialization JSON String to Java Object
✔️ Example JSON String
{"name":"Simone","age":28}
Deserialization Example
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDeserializationExample {
public static void main(String[] args) {
try {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"name\":\"Bhasker\",\"age\":28}";
User user = objectMapper.readValue(jsonString, User.class);
System.out.println("Name: " + user.getName());
System.out.println("Age: " + user.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Name: Bhasker
Age: 28
👉This shows how the JSON string is parsed and converted into a User
object.
3.2 Deserializing from a JSON File to Java Object
✔️ Example JSON File (user.json):
{
"name": "Bhasker",
"age": 28
}
✔️ Example Java Code:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
public class JacksonReadFileExample {
public static void main(String[] args) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File("user.json");
User user = objectMapper.readValue(jsonFile, User.class);
System.out.println("Name: " + user.getName());
System.out.println("Age: " + user.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}
👉This approach is helpful when working with large or persistent JSON data stored in files.
Output :
Name: Bhasker
Age: 28
✅ How Does Jackson Know How to Map JSON to Java Object?
Jackson relies on:
- Default Constructor: The target class must have a no-argument constructor (can be implicit).
- Getters and Setters: Jackson uses public setters to set values during deserialization.
- Field Matching: JSON property names must match Java field names, unless annotations (like
@JsonProperty
) are used to map them explicitly.
4. Jackson Annotations
Jackson provides useful annotations to control serialization and deserialization.
Common Jackson Annotations
- @JsonProperty → Maps a Java field to a specific JSON property name
- @JsonIgnore → Prevents a specific field from being serialized or deserialized.
- @JsonInclude → Controls inclusion of properties during serialization (e.g., omit nulls).
- @JsonIgnoreProperties → Prevents multiple unknown fields from causing exceptions during deserialization.
- @JsonCreator → Useful when deserializing immutable objects with final fields and no default constructor.
Learn more about Jackson Annotations here 👉 Common Jackson Annotations – A Complete Guide
✔️ Example : Employee.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Employee {
@JsonProperty("full_name")
private String name;
private int age;
@JsonIgnore
private String password;
public Employee() { }
public Employee(String name, int age, String password) {
this.name = name;
this.age = age;
this.password = password;
}
// Getters and Setters
}
Example Serialization
ObjectMapper objectMapper = new ObjectMapper();
Employee emp = new Employee("Ashish", 30, "secure123");
String jsonString = objectMapper.writeValueAsString(emp);
System.out.println(jsonString);
Output:
{"full_name":"Ashish","age":30}
5. Jackson Tree Model (JsonNode)
The Tree Model in Jackson represents JSON data as a hierarchical tree of JsonNode
objects.
Learn more about Jackson Tree Model (JsonNode) 👉 Jackson Tree Model (JsonNode) – Complete JSON Guide .
Example : How to Parse JSON into Tree Model
Json File
{
"name": "Ashish Kumar",
"age": 30,
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTreeExample {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"Ashish\",\"age\":30}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
System.out.println("Name: " + node.get("name").asText());
System.out.println("Age: " + node.get("age").asInt());
}
}
Output :
Name: Ashish
Age: 30
6. Handling Collections
✅ What Is Collection Handling?
Collection handling refers to the process of deserializing a JSON array into a Java collection (usually a List
, Set
, or Map
) of objects, and serializing a Java collection back into a JSON array.
For detailed information, please refer to the👉 Handling Collections in Jackson – Detailed Explanation
Example :
Input JSON String:
[
{"name":"Bhasker","age":28},
{"name":"Ashish","age":30}
]
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class JacksonListExample {
public static void main(String[] args) throws Exception {
String json = "[{\"name\":\"Bhasker\",\"age\":28}, {\"name\":\"Ashish\",\"age\":30}]";
ObjectMapper mapper = new ObjectMapper();
List < User > users = mapper.readValue(json, new TypeReference < List < User >> () {});
for (User u: users) {
System.out.println(u.getName() + " - " + u.getAge());
}
}
}
Output :
Bhasker - 28
Ashish - 30
7. Reading List of Objects from JSON File
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.List;
public class JacksonReadListFromFileExample {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File("users.json");
List<User> users = objectMapper.readValue(jsonFile, new TypeReference<List<User>>() {});
for (User user : users) {
System.out.println(user.getName() + " - " + user.getAge());
}
}
}
8. Pretty Printing JSON
When working with JSON data, especially for debugging, configuration files, or manual inspection, a compact JSON string without any formatting can be hard to read.
By default, Jackson produces a compact JSON output like this:
{"name":"Ashish Kumar","age":30}
This is fine for machine processing but not ideal for humans.
To make the JSON output more readable, we use Pretty Printing to add line breaks, indentation, and proper spacing.
✔️ Example
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JacksonPrettyPrintExample {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
User user = new User("Ashish Kumar", 30);
String prettyJson = objectMapper.writeValueAsString(user);
System.out.println(prettyJson);
}
}
Output:
{
"name" : "Ashish Kumar",
"age" : 30
}
9. Common Exceptions to Handle
JsonProcessingException
UnrecognizedPropertyException
MismatchedInputException
Summary of ObjectMapper Usage
Operation | Method Example |
---|---|
Serialize Object to String | writeValueAsString(obj) |
Serialize Object to File | writeValue(new File("output.json"), obj) |
Deserialize String to Object | readValue(jsonString, User.class) |
Deserialize File to Object | readValue(new File("user.json"), User.class) |
Read Tree Model | readTree(jsonString) |
Deserialize Array from File | readValue(new File("users.json"), new TypeReference<List<User>>(){}) |
Pretty Print | Enable SerializationFeature.INDENT_OUTPUT |
🎯Conclusion
Jackson is a powerful and flexible library that makes working with JSON in Java effortless. By mastering serialization, deserialization, annotations, tree model, file handling, collections, and pretty printing, you can efficiently handle JSON data in any Java project.