gson解析泛型数据

来源:互联网 发布:windows多线程编程 编辑:程序博客网 时间:2024/06/04 12:35

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;
    }
  }

原创粉丝点击