解析 List 的时候官方的使用:
List<Dim> dims=gson.fromJson(json,new TypeToken<List<Dim>>(){}.getType());
使用TypeToken 匿名内部类的方式.获取到匿名内部类定义的泛型.
当我们封装一个工具类的时候,解析 List 的时候不可避免要传递一个 TypeToken 匿名内部类的进来.
有什么办法只传递Dim
而不用写很长的 TypeToken 呢?
方式其实很简单,就是为 Gson 构造一个正确的 Type 给它.
TypeFactory是一个工具类简单封装.
/**
* Created by dim on 16/5/27.
*/
public class TypeFactory {
public static Type $List(Type type) {
return $Gson$Types.newParameterizedTypeWithOwner(null, List.class, type);
}
public static Type $Set(Type type) {
return $Gson$Types.newParameterizedTypeWithOwner(null, Set.class, type);
}
public static Type $HashMap(Type type, Type type2) {
return $Gson$Types.newParameterizedTypeWithOwner(null, HashMap.class, type, type2);
}
public static Type $Map(Type type, Type type2) {
return $Gson$Types.newParameterizedTypeWithOwner(null, Map.class, type, type2);
}
public static Type $Parameterized(Type ownerType, Type rawType, Type... typeArguments) {
return $Gson$Types.newParameterizedTypeWithOwner(ownerType, rawType, typeArguments);
}
public static Type $Array(Type type) {
return $Gson$Types.arrayOf(type);
}
public static Type $SubtypeOf(Type type) {
return $Gson$Types.subtypeOf(type);
}
public static Type $SupertypeOf(Type type) {
return $Gson$Types.supertypeOf(type);
}
}
使用:
List<Dim> dims = gson.fromJson(json, TypeFactory.$List(Dim.class));
再使用静态导入方法:
import static com.dim.TypeFactory.*;
...
List<Dim> dims = gson.fromJson(json, $List(Dim.class));
...
一些复杂的泛型
List<Dim> dims = gson.fromJson(json, $List(Dim.class));
List<List<Dim>> dimss= gson.fromJson(json,$List($List(Dim.class)));
Dim[] dimArray=gson.fromJson(json,$Array(Dim.class));
Set<Dim> dimSet=gson.fromJson(json,$Set(Dim.class));
Map<String,Dim> dimMap=gson.fromJson(json,$Map(String.class,Dim.class));
Map<String,List<Dim>> dimsMap=gson.fromJson(json,$Map(String.class,$List(Dim.class)));