近日需要json转换为bean,由于网上资料大都不符合本人预期,于是稍微查看源码学习了一下gjson对于泛型处理方式,并且抽象出方法进行封装,具体处理方式如下
一般泛型
//bean
public class User<T> {
T xxx,
......
}
public class User<T> {
List<T> xxx,
......
}
//转换方法
public static <C> User<C> parseResult(String result, Class<C> clazz) {
return GSON.fromJson(result, TypeToken.getParameterized(HttpsResult.class, clazz).getType());
}
嵌套泛型
//bean
public class User<T> {
T xxx,
......
}
public class Page<T> {
List<T> xxx,
......
}
//转换方法
protected static Type buildType(Type... types) {
ParameterizedTypeImpl beforeType = null;
if (types != null && types.length > 0) {
for (int i = types.length - 1; i > 0; i--) {
beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null ? types[i] : beforeType}, null, types[i - 1]);
}
}
return beforeType;
}
public static <C> User<Page<C>> parsePageResult(String result, Class<C> clazz) {
Type type = buildType(User.class, Page.class, clazz);
return GSON.fromJson(result, type);
}