Syngularity Syngularity - 4 months ago 21
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:

[{
"createdBy":"SYSTEM_INIT",
"status":401,
"message":"Unauthorized",
"description":"",
"lang":"en"
},{
"createdBy":"SYSTEM_INIT",
"status":413,
"message":"Payload Too Large",
"description":"The request is larger than the server is willing or able to process",
"lang":"en"
}{....


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
Class
object, with is
MyClass.class
. How can read in to a
Collection<MyClass>


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
LinkedHasMap
instead of
Collection
of
MyClass
with is in this particular sample is represented by variable
clazz
. Is there any way to do this?

Answer

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;
}