How to Use Jackson to Deserialize an Array of Objects in Java

Use Jackson to Deserialize an Array of Objects in Java

Jackson is a popular JSON library for Java that can easily convert JSON arrays into Java object arrays or collections In this tutorial, How to Use Jackson to Deserialize an Array of Objects in Java, we’ll explore several approaches using ObjectMapper.readValue() to parse a JSON array of objects. We’ll cover using a simple MyClass[], using TypeReference<List<MyClass>>, using TypeFactory.constructCollectionType, and the newer readerForListOf method. Each approach includes a code example plus pros and cons. (For more details, see the official Jackson documentation and Baeldung’s JSON tutorial{target=”_blank”}.)

Table of Contents

  • Using a MyClass[] Array
  • Using TypeReference<List<MyClass>>
  • Using constructCollectionType
  • Using readerForListOf
  • Generic Utility Method
  • Conclusion and Next Steps

Using a MyClass[] Array

The simplest way to deserialize a JSON array is by mapping it directly to a Java array type. Jackson’s ObjectMapper.readValue() lets you specify MyClass[].class to get an array of MyClass objects (java – How to use Jackson to deserialise an array of objects – Stack Overflow) (java – How to use Jackson to deserialise an array of objects – Stack Overflow). For example:

ObjectMapper mapper = new ObjectMapper();
MyClass[] myObjects = mapper.readValue(jsonString, MyClass[].class);

This code reads a JSON string like "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"}]" into a MyClass[]. You can then convert it to a List if needed (e.g. Arrays.asList(myObjects)). This approach is straightforward and type-safe because the array’s element type is explicit.

Pros:

  • Very concise syntax; no extra type tokens needed.
  • Produces a typed array (MyClass[]) directly.

Cons:

  • Returns a Java array, not a List (convert with Arrays.asList() if you need a list).
  • Less flexible for generic types (only works when the target type is exactly an array of the given class).
  • Your class must have a default constructor or proper annotations, or Jackson will error on instantiation (common Jackson requirement).

This method is well-documented in the Jackson ObjectMapper API. In fact, Jackson’s official guide shows using readValue(json, MyClass[].class) for arrays (java – How to use Jackson to deserialise an array of objects – Stack Overflow). (See also Jackson ObjectMapper docs for more.)

Using TypeReference<List<MyClass>>

If you prefer to work with List<MyClass> directly, use Jackson’s TypeReference to preserve generic type information. This involves creating an anonymous subclass of TypeReference with the desired generic type. For example:

List<MyClass> myList = mapper.readValue(
    jsonString, 
    new TypeReference<List<MyClass>>(){}
);

This code tells Jackson to deserialize the JSON array into a List<MyClass> rather than an array (java – How to use Jackson to deserialise an array of objects – Stack Overflow). It handles generics properly so you get a real List<MyClass> with type safety.

Pros:

  • Produces a List<MyClass> directly, which many APIs prefer.
  • Handles generic types correctly by preserving type information at runtime.

Cons:

  • Syntax is more verbose due to the anonymous inner class.
  • TypeReference instances can’t be reused for different types (you need a new one per call).
  • Less obvious to some developers (the anonymous class syntax looks a bit tricky).

This technique is a standard pattern in Jackson (see the TypeReference javadoc). The idea is to overcome Java’s type erasure, letting Jackson know the full generic type you want. It’s very common in examples and tutorials (java – How to use Jackson to deserialise an array of objects – Stack Overflow).

Using constructCollectionType

Jackson’s TypeFactory can build a JavaType for collection types, which you then pass to readValue(). This avoids the anonymous class of TypeReference. For example:

JavaType type = mapper.getTypeFactory()
                     .constructCollectionType(List.class, MyClass.class);
List<MyClass> myList = mapper.readValue(jsonString, type);

Or more compactly:

List<MyClass> myList = mapper.readValue(
    jsonString, 
    mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class)
);

This creates a JavaType representing List<MyClass> and tells Jackson to use it (java – How to use Jackson to deserialise an array of objects – Stack Overflow). The result is a List<MyClass> just like the TypeReference method.

Pros:

  • Avoids anonymous classes; the code is explicit about the collection type.
  • Flexible when you need to create types dynamically (e.g. from variables at runtime).
  • Useful in libraries or helper methods where you can’t write the generic type inline.

Cons:

  • Slightly more verbose than other methods.
  • A bit harder to read for beginners.
  • Involves an extra step (creating JavaType), though Jackson does this efficiently.

This approach is documented in Jackson’s TypeFactory API (see constructCollectionType in the TypeFactory javadoc). It’s essentially equivalent to the TypeReference example, but some developers prefer it for clarity.

Using readerForListOf

Starting in Jackson 2.11 (April 2020), there’s a built-in shortcut method readerForListOf that makes code cleaner (java – Jackson read json in generic List – Stack Overflow). It returns an ObjectReader configured for a List of the given class. Example:

List<MyClass> myList = mapper
    .readerForListOf(MyClass.class)
    .readValue(jsonString);

This is very concise: you directly pass the element class to readerForListOf and then call readValue() (java – How to use Jackson to deserialise an array of objects – Stack Overflow) (ObjectMapper (jackson-databind 2.11.0 API)). Jackson’s documentation describes readerForListOf(Class<?>) as “Factory method for constructing ObjectReader that will read… List<type>” (ObjectMapper (jackson-databind 2.11.0 API)).

Pros:

  • Extremely concise and readable. No need for TypeReference or TypeFactory.
  • Creates a reusable ObjectReader (if you keep it around), which can be faster in high-volume use.
  • Ideal for when you only need a simple List<MyClass>.

Cons:

Overall, readerForListOf is a very handy shorthand. If you see errors like readerForListOf(...) returns null, ensure you’re using a Jackson 2.11+ version (java – Jackson read json in generic List – Stack Overflow). Otherwise, it works great and is officially documented by FasterXML.

Generic Utility Method

To streamline your code, you can wrap these approaches in a generic helper method. For example, using constructCollectionType:

public static <T> List<T> parseJsonArray(String json, Class<T> clazz) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(
            json,
            mapper.getTypeFactory().constructCollectionType(List.class, clazz)
        );
    } catch (IOException e) {
        e.printStackTrace();
        return Collections.emptyList();
    }
}

Or using readerForListOf for brevity:

public static <T> List<T> parseJsonArray(String json, Class<T> clazz) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readerForListOf(clazz).readValue(json);
    } catch (IOException e) {
        e.printStackTrace();
        return Collections.emptyList();
    }
}

With such a method, you call parseJsonArray(jsonString, MyClass.class) and get back a List<MyClass>.

Pros:

  • Reduces repetitive code; centralizes JSON parsing logic.
  • Can handle exceptions internally and return an empty list or default.
  • Makes calling code cleaner (one-liner call).

Cons:

  • May hide exceptions (printing stack trace).
  • Instantiating a new ObjectMapper every time has some cost; consider reusing a static mapper if needed.

This utility encapsulates whichever approach you prefer. You could even allow callers to pass a TypeReference or JavaType for maximum flexibility. By practicing with these methods, you’ll get comfortable with Jackson’s features. (For related tutorials, see our JSON processing with Jackson and Spring Boot Jackson guide.)

Conclusion and Next Steps

In summary, Jackson makes it easy to deserialize a JSON array of objects. You can simply use MyClass[].class for an array, or choose a list-based approach with TypeReference, constructCollectionType, or readerForListOf. Each has trade-offs in code verbosity and flexibility. The MyClass[] array is the simplest, while TypeReference and constructCollectionType handle generics. The newer readerForListOf is very concise for lists (requiring Jackson 2.11+). Wrapping these in a generic utility method can save repetitive coding.

Now it’s your turn: practice by writing small JSON samples and deserializing them with Jackson. Try modifying the JSON structure or your class fields to see how Jackson behaves. Explore Jackson’s documentation and examples (such as the [ObjectMapper docs] or [Baeldung tutorial]) for more scenarios like handling nested objects or special type configurations.

Ready to become a Jackson pro? Experiment with these methods in your projects, and check out our other tutorials on JSON processing to deepen your understanding. Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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