How to use Jackson to deserialise an array of objects
Solution 1:
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
Solution 2:
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.
Solution 3:
For Generic Implementation:
public static <T> List<T> parseJsonArray(String json,
Class<T> classOnWhichArrayIsDefined)
throws IOException, ClassNotFoundException {
ObjectMapper mapper = new ObjectMapper();
Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
T[] objects = mapper.readValue(json, arrayClass);
return Arrays.asList(objects);
}
Solution 4:
First create an instance of ObjectReader which is thread-safe.
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<MyClass>>(){});
Then use it :
List<MyClass> result = objectReader.readValue(inputStream);