In GSON to get a list of objects you do
Gson gson = new Gson();
Type token = new TypeToken>(){}.getType();
return gson.fromJson(json
This has been answered in previous questions. Basically, there are 2 options:
Type
in from the calling site. The calling code will use TypeToken
or whatever to construct it.Type
corresponding to the parameterized type yourself. This will require you to write a class that implements ParameterizedType
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, "[{...}]");
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;
}
}
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);
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();
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