Java Type Generic as Argument for GSON

前端 未结 13 1813
陌清茗
陌清茗 2020-11-27 12:51

In GSON to get a list of objects you do

Gson gson = new Gson();
Type token = new TypeToken>(){}.getType();
return gson.fromJson(json         


        
13条回答
  •  孤独总比滥情好
    2020-11-27 13:13

    This work for everything. e.g. map which has a key and value generic.

    CustomType type = new CustomType(Map.class, String.class, Integer.class);
    

    So no more TokenType.

    class CustomType implements ParameterizedType {
        private final Class container;
        private final Class[] wrapped;
    
        @Contract(pure = true)
        public CustomType(Class container, Class... wrapped) {
            this.container = container;
            this.wrapped = wrapped;
        }
    
        @Override
        public Type[] getActualTypeArguments() {
            return this.wrapped;
        }
    
        @Override
        public Type getRawType() {
            return this.container;
        }
    
        @Override
        public Type getOwnerType() {
            return null;
        }
    }
    

提交回复
热议问题