Java Type Generic as Argument for GSON

前端 未结 13 1701
陌清茗
陌清茗 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:10

    This has been answered in previous questions. Basically, there are 2 options:

    1. Pass the Type in from the calling site. The calling code will use TypeToken or whatever to construct it.
    2. Construct a Type corresponding to the parameterized type yourself. This will require you to write a class that implements ParameterizedType
    0 讨论(0)
  • 2020-11-27 13:12
    public static final <T> List<T> getList(final Class<T[]> clazz, final String json)
    {
        final T[] jsonToObject = new Gson().fromJson(json, clazz);
    
        return Arrays.asList(jsonToObject);
    }
    

    Example:

    getList(MyClass[].class, "[{...}]");
    
    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:19
      public static <T> T getObject(String gsonStr) {
            Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();
            Type collectionType = new TypeToken< T>(){}.getType();
            return gson.fromJson(gsonStr,
                    collectionType);
        }
    

    When use:

    Class1 class1=  getObject(jsonStr);
    
    0 讨论(0)
  • 2020-11-27 13:21

    Since gson 2.8.0, you can use TypeToken#getParametized((Type rawType, Type... typeArguments)) to create the typeToken, then getType() should do the trick.

    For example:

    TypeToken.getParameterized(List.class, myType).getType();
    
    0 讨论(0)
  • 2020-11-27 13:25

    Here is the full code base on great answer from @oldergod

    public <T> List<T> fromJSonList(String json, Class<T> myType) {
        Gson gson = new Gson();
        Type collectionType = TypeToken.getParameterized(List.class, myType).getType();
        return gson.fromJson(json, collectionType);
    }
    

    Using

    List<MyType> myTypes = parser.fromJSonList(jsonString, MyType.class);
    

    Hope it help

    0 讨论(0)
提交回复
热议问题