Gson TypeToken with dynamic ArrayList item type

前端 未结 9 2001
情深已故
情深已故 2020-11-22 08:55

I have this code:

Type typeOfObjectsList = new TypeToken>() {}.getType();
List objectsList = new Gson().fromJso         


        
9条回答
  •  一生所求
    2020-11-22 09:05

    Fully working solution:

    String json = .... //example: mPrefs.getString("list", "");
    ArrayList myTypes = fromJSonList(json, YouClassName.class);
    
    
    public  ArrayList fromJSonList(String json, Class type) {
            Gson gson = new Gson();
            return gson.fromJson(json, TypeToken.getParameterized(ArrayList.class, type).getType());
        }
    

提交回复
热议问题