You can use below class to read list of objects. It contains static method to read a list with some specific object type. It is included Jdk8Module changes which provide new time class supports too. It is a clean and generic class.
List<Student> students = JsonMapper.readList(jsonString, Student.class);
Generic JsonMapper class:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.util.*;
import java.util.Collection;
public class JsonMapper {
public static <T> List<T> readList(String str, Class<T> type) {
return readList(str, ArrayList.class, type);
}
public static <T> List<T> readList(String str, Class<? extends Collection> type, Class<T> elementType) {
final ObjectMapper mapper = newMapper();
try {
return mapper.readValue(str, mapper.getTypeFactory().constructCollectionType(type, elementType));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static ObjectMapper newMapper() {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new JavaTimeModule());
mapper.registerModule(new Jdk8Module());
return mapper;
}
}