【发布时间】:2017-04-15 16:04:08
【问题描述】:
在将 json 响应映射到 pojo 的改造中,我们通常会这样做
@POST
Call<User> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);
ApiCalls api = retrofit.create(ApiCalls.class);
Call<User> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<User>() {
//Response and failure callbacks
}
其中 User 是我的 Pojo 类。 但是对于每个其他请求,我需要制作不同的 pojo 并为改造调用编写相同的代码。我想制作一个调用 api 的方法并将相应的 pojo 类传递给改造调用。像这样
ApiCalls api = retrofit.create(ApiCalls.class);
Call<*ClassPassed*> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<*ClassPassed*>() {
//Response and failure callbacks
}
所以现在我可以将任何 pojo 类转换为单个方法并获得响应。这只是为了避免一次又一次地重写相同的代码。这可能吗
更新 详细说明:
假设我需要提出两个请求。第一个是获取 userDetails,另一个是 PatientDetails。所以我必须创建两个模型类 User 和 Patient。 所以在改造 api 中我会有这样的东西
@POST
Call<User> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);
@POST
Call<Patient> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);
在我的 FragmentUser 和 FragmentPatient 类中我会这样做
ApiCalls api = retrofit.create(ApiCalls.class);
Call<User> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<User>() {
//Response and failure callbacks
}
ApiCalls api = retrofit.create(ApiCalls.class);
Call<Patient> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<Patient>() {
//Response and failure callbacks
}
但是这里的代码只是因为不同的 pojo 类而重复。我需要在每个其他片段中重复相同的代码以处理不同的请求。 所以我需要创建一个通用方法,它可以接受任何 pojo 类,然后从片段中传递要映射的 pojo。
【问题讨论】:
-
什么?这正是 Retrofit 试图阻止的!如果你想做这样的事情,最好使用另一个库,或者只使用没有改造的 OkHttp,或者使用 Ion/Volley/Some other random http lib
-
@sushildlh:更新问题请查收。
-
@Androidjack 看看答案,我想它对你有帮助....
标签: android retrofit retrofit2 pojo