Deserializing an Array of Objects with Jackson
Jackson documentation claims support for deserializing arrays of objects, but the specific syntax might be unclear. Let's explore two approaches for deserializing an array of objects.
Serialization Considerations
Consider the following JSON input for an array of objects:
[{ "id" : "junk", "stuff" : "things" }, { "id" : "spam", "stuff" : "eggs" }]
Deserialization Approach 1: As Array
Instantiate an ObjectMapper and use readValue to deserialize the input as an array of the target object type:
// Instantiate an ObjectMapper ObjectMapper mapper = new ObjectMapper(); // Deserialize JSON into an array of MyClass objects MyClass[] myObjects = mapper.readValue(jsonInput, MyClass[].class);
Deserialization Approach 2: As List
To deserialize the input as a list, one can use new TypeReference or constructCollectionType:
Option a: Using TypeReference
// Create TypeReference for a list of MyClass objects TypeReference<List<MyClass>> typeRef = new TypeReference<List<MyClass>>() {}; // Deserialize JSON input using the TypeReference List<MyClass> myObjects = mapper.readValue(jsonInput, typeRef);
Option b: Using constructCollectionType
// Create a CollectionType for a list of MyClass objects JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class); // Deserialize JSON input using the CollectionType List<MyClass> myObjects = mapper.readValue(jsonInput, type);
With these approaches, you can flexibly deserialize arrays of objects into desired data structures in Java using Jackson.
The above is the detailed content of How to Deserialize an Array of Objects in Jackson using Java?. For more information, please follow other related articles on the PHP Chinese website!