改造-解析具有基类的通用api响应 [英] Retrofit - Parsing generic api response with base class
问题描述
我正在为我的android应用程序开发对rest api调用进行改造.由于我的所有api响应都具有"info"
(请注意所有api将具有相同的键名)和"data"
(请注意不同的api具有不同的键名)参数,因此我使用了一个基类api响应.以下是来自API的示例响应
I am using retrofit for rest api calls for my android app development. Since my all api response has "info"
(Note that all api will have same key name) and "data"
(Note that different apis have different key names) parameter, I have used a base class for the api responses. Below are the sample responses from API
响应1
{
"info":{
"statusCode":200,
"message":"OK"
},
"data":{
"userId":2,
"userName":"riyas"
}
}
响应2
{
"info":{
"statusCode":200,
"message":"OK"
},
"data":{
"vegId":2,
"vegName":"Potatoa"
}
}
我创建了一个名为 CloudBaseResponse 的基类,并且能够在 response.info
中获取数据.但是我不知道解析**data**
.请为我建议使用 Retrofit
I have created a base class named CloudBaseResponse and was able to get data in response.info
. But I have no idea to parse the **data**
. Please suggest me a way to handle using Retrofit
public class CloudBaseResponse {
public BaseResponse response;
public BaseResponse getResponse() {
return response;
}
public void setResponse(BaseResponse response) {
this.response = response;
}
public class BaseResponse {
public Info info;
}
public class Info{
public String status;
public String message;
}
}
推荐答案
您可以使用Generics
映射您的api响应.
You can use Generics
to map your api response.
public class CloudBaseResponse<T> {
@SerializedName("info")
private Info info;
@SerializedName("data")
private T data;
// Getters Setters..
}
public class Info {
private String status;
private String message;
// Getters Setters..
}
例如,您有一个Vegetable
类.
public class Vegetable {
private int vegetableId;
private String vegetableName;
// Getters Setters..
}
稍后可以与Retrofit
一起使用,如以下代码所示:
Later you can use with Retrofit
like the following code:
Call<CloudBaseResponse<Vegetable>> getVegetables();
这篇关于改造-解析具有基类的通用api响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!