Handling Collections in Jackson – Detailed Explanation

When working with JSON data in real-world applications, it is very common to deal with collections, especially lists of objects.
Jackson provides easy and powerful mechanisms to handle JSON arrays and convert them into Java collections, such as List<User>.

1. 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.

2. Why Is This Important?

  • API responses often return lists of items (e.g., list of users, orders, products).
  • Data persistence can involve storing or reading multiple records in a structured JSON array format.
  • Allows batch processing of JSON data.

3. Example JSON Array

[
    { "name": "Simone", "age": 28 },
    { "name": "Ashish", "age": 30 },
    { "name": "Ravi", "age": 25 }
]

This JSON represents a list of User objects.

4. How Jackson Maps JSON Array to List of Objects

✅ Step-by-Step Example:

Define the User 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
}

4.1. Deserialize JSON Array into List<User>

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.List;

public class JacksonCollectionDeserializationExample {
  public static void main(String[] args) {
    try {
      ObjectMapper objectMapper = new ObjectMapper();

      // Read JSON array from file
      File jsonFile = new File("users.json");

      // Deserialize JSON array into List<User>
      List < User > users = objectMapper.readValue(jsonFile, new TypeReference < List < User >> () {});

      // Iterate over users
      for (User user: users) {
        System.out.println("Name: " + user.getName() + ", Age: " + user.getAge());
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

➤ Explanation of Key Concepts:

  • new TypeReference<List<User>>() {} is necessary because of Java’s type erasure:
    It tells Jackson the full generic type to deserialize into, since List<User> cannot be determined at runtime without help.
  • The JSON file (users.json) contains an array of user objects.
✔️ Example Output:
Name: Simone, Age: 28  
Name: Ashish, Age: 30  
Name: Ravi, Age: 25  

4.2. Serializing List<User> to JSON Array

You can also serialize a List<User> into a JSON array like this:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class JacksonCollectionSerializationExample {
    public static void main(String[] args) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();

            List<User> users = new ArrayList<>();
            users.add(new User("Simone", 28));
            users.add(new User("Ashish", 30));
            users.add(new User("Ravi", 25));

            // Serialize list to JSON file
            objectMapper.writeValue(new File("users_output.json"), users);

            System.out.println("JSON array written to users_output.json successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The resulting users_output.json will look like:

[
    {"name":"Simone","age":28},
    {"name":"Ashish","age":30},
    {"name":"Ravi","age":25}
]

5. Why Is TypeReference Important?

Without TypeReference, Jackson doesn’t know at runtime what generic type to use.
For example:

List<User> users = objectMapper.readValue(jsonArray, List.class);

would return a List<Map<String, Object>> instead of List<User>.

By using:

new TypeReference<List<User>>() {}

Jackson understands the correct mapping.

6. When to Use Collection Handling

ScenarioUse Case
API returns a list of entitiesDeserialize JSON array into List<User>
Bulk data persistenceSerialize List<User> into JSON array in a file
Data transformationMap JSON array to Java collection, then manipulate data

✅ Conclusion

Handling collections is a critical aspect of real-world JSON processing.
Jackson’s combination of TypeReference, ObjectMapper.readValue(), and writeValue() makes it effortless to convert JSON arrays into Java collections and back.
This ensures efficient, type-safe handling of structured batch data from APIs, configuration files, or persistent storage.

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *