Syngularity Syngularity - 6 months ago 24
JSON Question

how to read json into collection knowing only Class of the entity with jackson ObjectMapper

I have a json file witch contains a list of a given type, for example:

"message":"Payload Too Large",
"description":"The request is larger than the server is willing or able to process",

I have a java class(this case call it MyClass) witch represent this one entity.
When i want to deserialize the json into collection i only have a
object, with is
. How can read in to a

Actually it"s a spring applicaiton and this is my current code:

public boolean importFromJsonFile(String table, Class clazz) {
Collection<Object> objectCollection = new ArrayList<>();

ObjectMapper mapper = new ObjectMapper();
try {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("init/" + table + ".import.json").getFile());
objectCollection = mapper.readValue(file, Collection.class);
}catch (Exception e){
log.error("error: ", e);
return false;

if(objectCollection.size() < 0){
log.error("There is no data in the file");
return false;

try {
for(Object obj : objectCollection){
save(obj, clazz);
}catch (Exception e){
log.error("fatal error: ", e);
return false;

return true;

So my problem after reading the file the result will be a Collection of
instead of
with is in this particular sample is represented by variable
. Is there any way to do this?


There's way

List<MyClass> myObjects = Arrays.asList(mapper.readValue(file, MyClass[].class))

You can get different approaches here, however, this one is faster.

Based on the comments(As It is mentioned that class variable and file is present on the runtime):

public List getObjects(Class<T> aClass, File file) throws ClassNotFoundException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    //Fetches Arrayed Class
    Class namedClass = Class.forName("[L" + aClass.getName() + ";");
    List myObjects = Arrays.asList(mapper.readValue(file, namedClass));
    return myObjects;