public <T> OnHttpResultListener jsonHttpWithData(Class<T> clazz, OnUiCallback<T> onUiCallback, OnNextListener<T> onNextListener) {
return new OnHttpResultListener() {
@Override
public void onSuccess(String s) {
if (!TextUtils.isEmpty(s)) {
GsonResponsePasare<T> pasare = new GsonResponsePasare<T>() {
};
ResponseResult<T> responseResult = pasare.deal(s);
LogUtils.i(TAG, "responseResult ==" + new Gson().toJson(responseResult));
jsonData(responseResult, onUiCallback, onNextListener);
} else {
if (onUiCallback != null) {
onUiCallback.onError(EXC_CODE, JSON_NULL);
}
}
}
@Override
public void onError(Throwable e) {
onUiCallback.onError(EXC_CODE, e.getMessage() == null ? "" : e.getMessage());
}
};
}
class GsonResponsePasare<T> implements ParameterizedType {
public ResponseResult<T> deal(String response) {
// Type gsonType = new ParameterizedType() {//...};//不建议该方式,推荐采用GsonResponsePasare实现ParameterizedType.因为getActualTypeArguments这里涉及获取GsonResponsePasare的泛型集合
Type gsonType = this;
ResponseResult<T> result = new Gson().fromJson(response, gsonType);
// LogUtils.e("Data is : " + commonResponse.data, "Class Type is : " + commonResponse.data.getClass().toString());
return result;
}
@NotNull
@Override
public Type[] getActualTypeArguments() {
Class clz = this.getClass();
//这里必须注意在外面使用new GsonResponsePasare<GsonResponsePasare.DataInfo>(){};实例化时必须带上{},否则获取到的 superclass 为Object
Type superclass = clz.getGenericSuperclass(); //getGenericSuperclass()获得带有泛型的父类
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
Type[] types = parameterized.getActualTypeArguments();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
LogUtils.i(TAG, "getActualTypeArguments types =" + types[0].getTypeName());
}
return types;
}
@Override
public Type getOwnerType() {
return null;
}
@Override
public Type getRawType() {
return ResponseResult.class;
}
}
public OnHttpResultListener jsonLogin(OnUiCallback<Token> callback) {
return jsonHttpWithData(Token.class, callback, new OnNextListener<Token>() {
@Override
public void onNext(Token token) {
CacheDataModel.getInstance().saveLoginData(token);
}
});
}
调用:
jsonLogin 开始
异常:
Caused by: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.xx.xx.entity.response.VehicleBindingList
请求结果共用了ResponseResult<T> result = new Gson().fromJson(response, gsonType);
问题原因:泛型没有指定具体类型。
想问一下怎么解决,想共用fromJson这行代码