[英]Retrofit Custom Callback Generic Type
我正在擴展默認的 Retrofit 2 回調:
abstract class APICallback<T> implements Callback<T> {
@Override
public void onResponse(Call<T> call, Response<T> response) {
if (!response.isSuccessful()) {
// Cast response.body() to my POJO class, results in null
MyClass myClass = (MyClass) response.body();
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
// TODO ...
}
}
如何將 Response 的通用類型向下轉換為我自己的類? 這個過程應該是自動的嗎? 我正在為客戶端使用 GsonConverter。
我認為您必須修改 AdapterFactory 然后注冊改造
public class APICallAdapterFactory extends CallAdapter.Factory {
@Nullable
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
final Type responseType = ((ParameterizedType) returnType).getActualTypeArguments()[0];
return new CallAdapter<Object, Object>() {
@Override
public Type responseType() {
return responseType;
}
@Override
public Object adapt(Call<Object> call) {
return new APICallAdapter<>(call);
}
};
}
和
private static Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIService.baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(new APICallAdapterFactory())
.build();
用 MyClass 替換 T
class APICallback implements Callback<MyClass> {
@Override
public void onResponse(Call<MyClass> call, Response<MyClass> response) {
if (response.isSuccessful()) {
// Cast response.body() to my POJO class, results in null
MyClass myClass = response.body();
}
}
@Override
public void onFailure(Call<MyClass> call, Throwable t) {
}
}
你可以通過這個處理
Gson gson = new Gson();
MyClass myClass = gson.fromJson(response.body(), MyClass.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.