Gson TypeToken with dynamic ArrayList item type

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

I have this code:

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


        
9条回答
  •  情歌与酒
    2020-11-22 09:10

    Option 1 - implement java.lang.reflect.ParameterizedType yourself and pass it to Gson.

    private static class ListParameterizedType implements ParameterizedType {
    
        private Type type;
    
        private ListParameterizedType(Type type) {
            this.type = type;
        }
    
        @Override
        public Type[] getActualTypeArguments() {
            return new Type[] {type};
        }
    
        @Override
        public Type getRawType() {
            return ArrayList.class;
        }
    
        @Override
        public Type getOwnerType() {
            return null;
        }
    
        // implement equals method too! (as per javadoc)
    }
    

    Then simply:

    Type type = new ListParameterizedType(clazz);
    List list = gson.fromJson(json, type);
    

    Note that as per javadoc, equals method should also be implemented.

    Option 2 - (don't do this) reuse gson internal...

    This will work too, at least with Gson 2.2.4.

    Type type = com.google.gson.internal.$Gson$Types.newParameterizedTypeWithOwner(null, ArrayList.class, clazz);
    

提交回复
热议问题