I'm trying to make the import From JSON method universal for working with different classes. But I'm confused about these generics.
private <T> List<T> importFromJSON(DataItems<T> dataItems) {
try(FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader streamReader = new InputStreamReader(fileInputStream)){
Gson gson = new Gson();
dataItems = gson.fromJson(streamReader, DataItems<>.class);
return dataItems.getList();
}
catch (IOException ex){
ex.printStackTrace();
}
return null;
}
public class DataItems<E> {
private List<E> list;
public List<E> getList() {
return list;
}
public void setList(List<E> list) {
this.list = list;
}
}
public class House {
int number;
String name;
}
json file
{"list":[{"name":"01","id":1},{"name":"02","id":2}]}
I call this method already with a specific type
DataItems<House> dataItems = new DataItems<>();
importFromJSON(dataItems);
Everything is readable, as a result of executing import From JSON, I get a list of objects, but only instead of the int type, for some reason there is a Double type And when trying to pull an object from this list
House house = (House) list.get(0);
получаю Exception:
java.lang.ClassCastException LinkedTreeMap cannot be cast to House