@act262
2017-03-24T03:26:43.000000Z
字数 1396
阅读 2456
Gson
定义的一些类:
// 普通对象
class CustomObj {
int id;
String name;
}
// 带泛型的对象
class GenericObj<T> {
int id;
T data;
}
1.处理一般的对象:
CustomObj obj = gson.fromJson(jsonContent,CustomObj.class);
2.处理带泛型的对象:
带泛型的模型一般用匿名内部类的形式创建TypeToken
,从而获取到带泛型参数的Type
用于gson解析
Type type = new TypeToken<GenericObj<String>>() {}.getType()
GenericObj<String> o = gson.fromJson(jsonContent, type)
可以将方法1中的class
转换为Type
,然后流程和方法2是一样的,没必要.
Type type = new TypeToken<CustomObj>() {}.getType()
CustomObj obj = gson.fromJson(jsonContent,type);
TypeToken作用:
使用Java的泛型功能时,因为泛型的擦除机制,所以在运行时不能知道泛型的具体类型是什么,TypeToken
就是用来保留这个泛型信息的.
// 泛型的真实类型
final Class<? super T> rawType;
// 使用泛型的那个类
final Type type;
final int hashCode;
protected TypeToken() {
this.type = getSuperclassTypeParameter(getClass());
this.rawType = (Class<? super T>) $Gson$Types.getRawType(type);
this.hashCode = type.hashCode();
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
// 这里指代的是TypeToken<T>这个类
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
使用JsonDeserializer
的泛型参数
JsonDeserializer deserializer = xxx;
Type ifGenericType = deserializer.getClass().getGenericInterfaces()[0];
ParameterizedType parameterizedType = (ParameterizedType) ifGenericType;
Type type = $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);