mercredi 22 juin 2016

Load JSON with GSON and reflection and generics

I want to load a JSON with GSON which works as long as I set the type. But I'd like to have a "generic" version of my loader, something like this:

public static <T> HashMap<String, T> loadJSON(String path,String className){
    try {

        //T is of type className

        HashMap<String, T> map;
        Gson gson=new Gson();
        T[] data=gson.fromJson(new FileReader(path), T[].class);

        //fill map with data

        return map;
    } catch (Exception ex) {}
}

Of course I get "cannot select from a type variable" because T[].classis not a valid parameter. Is it possible to achieve what I want?





Aucun commentaire:

Enregistrer un commentaire