Gson TypeToken with dynamic ArrayList item type

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

I have this code:

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


        
9条回答
  •  爱一瞬间的悲伤
    2020-11-22 09:15

    You can actually do it. You just need to parse first your data into an JsonArray and then transform each object individually, and add it to a List :

    Class dataType;
    
    //...
    
    JsonElement root = jsonParser.parse(json);
    List data = new ArrayList<>();
    JsonArray rootArray = root.getAsJsonArray();
    for (JsonElement json : rootArray) {
        try {
            data.add(gson.fromJson(json, dataType));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return data;
    

提交回复
热议问题