I am trying to write a convenient method to read a List of objects from different files. Right now I have this one:
public <T> List<T> parseList(String file) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try (Reader reader = new InputStreamReader(loader.getResourceAsStream(file))) {
return gson.fromJson(gson.newJsonReader(reader), new TypeToken<ArrayList<T>>(){}.getType());
} catch (Exception e){
LOGGER.error("Cannot read json file "+ file, e);
throw new JBCCannotReadFileException(e);
}
}
When I try to use this method like:
List<MyObject> myList = parseList(filtPath);
It returns List<LinkedTreeMap<...>>
. The strange thing also is that it successfully assigns that value to List<MyObject>
and after I try to access myList
it throws an exception that LinkedTreeMap
cannot be converted into MyObject
.
When I use new TypeToken<ArrayList<MyObject>>(){}.getType()
instead of new TypeToken<ArrayList<T>>(){}.getType()
it works as expected but when the type is generic (T
) it works really strange. Is there a way to fix the above method?