gson解析泛型數據

public class BaseResponseBean<T> {
  private Integer code;


  private String msg;


  private T data;


  public Integer getCode() {
    return code;
  }


  public void setCode(Integer code) {
    this.code = code;
  }


  public String getMsg() {
    return msg;
  }


  public void setMsg(String msg) {
    this.msg = msg;
  }


  public T getData() {
    return data;
  }


  public void setData(T data) {
    this.data = data;
  }



/** 自定義ParameterizedTypeImpl 解析到 */
  public static <T> BaseResponseBean<T> GsonToNetObject(String jsonString, Class<T> clazz) {
    ParameterizedTypeImpl parameterizedType =
        new ParameterizedTypeImpl(BaseResponseBean.class, new Class[] { clazz });
    Gson gson = new Gson();
    return gson.fromJson(jsonString, parameterizedType);
  }


  /** 自定義ParameterizedTypeImpl 解析到 */
  public static <T> BaseResponseBean<List<T>> GsonToNetList(String jsonString, Class<T> clazz) {
    // 生成List<T> 中的 List<T>
    ParameterizedTypeImpl parameterizedType =
        new ParameterizedTypeImpl(List.class, new Class[] { clazz });
    // 根據List<T>生成完整的Result<List<T>>
    ParameterizedTypeImpl parameterizedType1 =
        new ParameterizedTypeImpl(BaseResponseBean.class, new Type[] { parameterizedType });


    Gson gson = new Gson();
    return gson.fromJson(jsonString, parameterizedType1);
  }


  /** 參照:搞定Gson泛型封裝 http://www.jianshu.com/p/d62c2be60617 */
  public static class ParameterizedTypeImpl implements ParameterizedType {
    private final Class raw;
    private final Type[] args;


    public ParameterizedTypeImpl(Class raw, Type[] args) {
      this.raw = raw;
      this.args = args != null ? args : new Type[0];
    }


    @Override public Type[] getActualTypeArguments() {
      return args;
    }


    @Override public Type getRawType() {
      return raw;
    }


    @Override public Type getOwnerType() {
      return null;
    }
  }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章