java - Deserialise a generic list in Gson -


i want write generic function deserialise generic type list gson here code:

private <t> list<t> getlistfromfile(string filename)     {         //read textfile         bufferedreader reader;         string data="";         try          {             reader = new bufferedreader(new filereader(filename));             data = reader.readline();             reader.close();         }          catch (filenotfoundexception ex)          {          }          catch (ioexception ex)          {          }         if (data == null)          {             list<t> spiel = new arraylist<t>();             return spiel;         }         else         {             //get list deserialise             gson gson = new gson();             list<t> = gson.fromjson(data, new typetoken<list<t>>(){}.gettype());             return something;         }     } 

but code not working, strange structure not list of type

when i'am using:

list<concretetype> = gson.fromjson(data, new typetoken<list<t>>(){}.gettype()); 

i works list<concretetype>!!

but need generic function, how can fix it?

regards rubiktubik

there no way without passing actual type of t (as class<t>) method.

but if pass explicitly, can create typetoken list<t> follows:

private <t> list<t> getlistfromfile(string filename, class<t> elementtype) {     ...     typetoken<arraylist<t>> token = new typetoken<arraylist<t>>() {};     list<t> = gson.fromjson(data, token.gettype());     ... } 

see also:


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -