[关闭]
@act262 2017-03-24T03:26:43.000000Z 字数 1396 阅读 2311

Gson Java 泛型解析

Gson


image_1bbt251u011b310tbuhb1ap11bu99.png-40.4kB

定义的一些类:

  1. // 普通对象
  2. class CustomObj {
  3. int id;
  4. String name;
  5. }
  6. // 带泛型的对象
  7. class GenericObj<T> {
  8. int id;
  9. T data;
  10. }

1.处理一般的对象:

  1. CustomObj obj = gson.fromJson(jsonContent,CustomObj.class);

2.处理带泛型的对象:
带泛型的模型一般用匿名内部类的形式创建TypeToken,从而获取到带泛型参数的Type用于gson解析

  1. Type type = new TypeToken<GenericObj<String>>() {}.getType()
  2. GenericObj<String> o = gson.fromJson(jsonContent, type)

可以将方法1中的class转换为Type,然后流程和方法2是一样的,没必要.

  1. Type type = new TypeToken<CustomObj>() {}.getType()
  2. CustomObj obj = gson.fromJson(jsonContent,type);

TypeToken作用:
使用Java的泛型功能时,因为泛型的擦除机制,所以在运行时不能知道泛型的具体类型是什么,TypeToken就是用来保留这个泛型信息的.

  1. // 泛型的真实类型
  2. final Class<? super T> rawType;
  3. // 使用泛型的那个类
  4. final Type type;
  5. final int hashCode;
  1. protected TypeToken() {
  2. this.type = getSuperclassTypeParameter(getClass());
  3. this.rawType = (Class<? super T>) $Gson$Types.getRawType(type);
  4. this.hashCode = type.hashCode();
  5. }
  6. static Type getSuperclassTypeParameter(Class<?> subclass) {
  7. // 这里指代的是TypeToken<T>这个类
  8. Type superclass = subclass.getGenericSuperclass();
  9. if (superclass instanceof Class) {
  10. throw new RuntimeException("Missing type parameter.");
  11. }
  12. ParameterizedType parameterized = (ParameterizedType) superclass;
  13. return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
  14. }

使用JsonDeserializer的泛型参数

  1. JsonDeserializer deserializer = xxx;
  2. Type ifGenericType = deserializer.getClass().getGenericInterfaces()[0];
  3. ParameterizedType parameterizedType = (ParameterizedType) ifGenericType;
  4. Type type = $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注