Gson TypeToken with dynamic ArrayList item type

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

I have this code:

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


        
9条回答
  •  囚心锁ツ
    2020-11-22 09:24

    sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl workes. No need for custom implementation

    Type type = ParameterizedTypeImpl.make(List.class, new Type[]{childrenClazz}, null);
    List list = gson.fromJson(json, type);
    

    Can be used with maps and any other collection:

    ParameterizedTypeImpl.make(Map.class, new Type[]{String.class, childrenClazz}, null);
    

    Here is nice demo how you can use it in custom deserializer: Deserializing ImmutableList using Gson

提交回复
热议问题