0

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
alex
  • 324
  • 1
  • 8
  • 28
  • 1
    https://stackoverflow.com/questions/18397342/deserializing-generic-types-with-gson – luk2302 Sep 25 '22 at 17:37
  • The thing is that generics in Java are there to provide extended static time type checking. At runtime, generics are erased. So if I understand your question correctly, it is not possible to do what you are trying to do with generics in Java – ControlAltDel Sep 25 '22 at 17:49
  • Instead, I recommend using the factory pattern where you can add type handlers (ie handler registers for handling of one type of message through some form of identification) – ControlAltDel Sep 25 '22 at 17:52
  • I don't quite understand what you mean? – alex Sep 27 '22 at 17:24
  • Does this answer your question? [Deserializing Generic Types with GSON](https://stackoverflow.com/questions/18397342/deserializing-generic-types-with-gson) – knittl Oct 19 '22 at 06:50

0 Answers0