英文:
Retrofit 2 - How to make request without Call object
问题
Sure, here is the translated version of the content you provided:
使用 Retrofit 2,我有一个带有 REST 方法的 UserService,它返回对象 Call<?>。
我想调用这些方法并只返回数据对象。
我有以下代码:
@GET("users")
Call<List<UserDTO>> getUsers();
但我想要的是:
@GET("users")
List<UserDTO> getUsers();
我知道在 Retrofit 1.9 中默认情况下是可能的,但我找不到解决此问题的方法。
每次使用时,我都不想调用方法,执行调用,获取主体并进行 try..catch。
当我从第二个示例中调用方法时,我收到错误:
找不到 java.util.List<> 的调用适配器
是否有可能在任何适配器中处理此情况?如何做到?
英文:
I use retrofit 2 and I have UserService with rest methods which return objects Call<?>.
I would like to invoke these methods and return just data object.
I have this:
@GET("users")
Call<List<UserDTO>> getUsers();
but I want:
@GET("users")
List<UserDTO> getUsers();
I know that was possible by default in retrofit 1.9 but i couldn't find solution for this problem.
I dont want invoke method, execute call, get body and make try..catch every time when I use it.
When I invoke method from my second example I receive error:
Could not locate call adapter for java.util.List<>
Is it possible to handle this case in any adapter? And how to do it ?
答案1
得分: 3
我是你的中文翻译,以下是你提供的代码部分的翻译:
我是这样解决这个问题的:
public class CustomCallAdapter<T> implements CallAdapter<T, T> {
private Type returnType;
public CustomCallAdapter(Type returnType) {
this.returnType = returnType;
}
@Override
public Type responseType() {
return returnType;
}
@Override
public T adapt(Call<T> call) {
try {
return call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static class Factory extends CallAdapter.Factory {
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
return new CustomCallAdapter(returnType);
}
}
}
请注意,以上只是你提供的代码部分的中文翻译。
英文:
I resolved this problem like that:
public class CustomCallAdapter<T> implements CallAdapter<T, T> {
private Type returnType;
public CustomCallAdapter(Type returnType) {
this.returnType = returnType;
}
@Override
public Type responseType() {
return returnType;
}
@Override
public T adapt(Call<T> call) {
try {
return call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static class Factory extends CallAdapter.Factory {
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
return new CustomCallAdapter(returnType);
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论