英文:
Passing different data to same name json attribute in retrofit model
问题
public class Response {
private boolean success;
private String message;
private Data data;
public boolean isSuccess() {
return success;
}
public String getMessage() {
return message;
}
public Data getData() {
return data;
}
}
public class Data {
// Define fields based on the possible data themes
// For the first data theme
private String update_status;
private String last_version_name;
private String last_version_code;
private boolean need_to_upgrade;
// For the second data theme
private String year;
private String month;
private String day;
private String hour;
private String second;
private String unix;
// Generate getters for each field
// ...
}
英文:
There is a WebService which i want to @GET and @POST data from it, but all of its responses are like this theme:
{
"data": {
...
},
"success": ... ,
"message": ...
}
but there are different output themes of data, like these:
{
"data": {
"update_status": "critical",
"last_version_name": "1.0.3",
"last_version_code": "3",
"need_to_upgrade": false
},
"success": true,
"message": "DONE!"
}
&
{
"data": {
"year": "2020",
"month": "09",
"day": "09",
"hour": "06",
"second": "00",
"unix": "1599631246"
},
"success": true,
"message": null
}
How can i define models to use this via Retrofit and GSON Converter?
Should i use @SerializedName somewhere?
(i.e:)
public class Response{
private boolean success;
private String message;
//private Data data
}
答案1
得分: 1
创建一个基础合约,并通过所有响应类进行扩展。在合约中,data
部分将是通用的。
public class BaseResponse<T> {
public boolean success;
public String message;
public T data;
}
现在,你需要为每种类型的响应创建数据类。
public class MyResponse {
public String update_status;
public String last_version_name;
public String last_version_code;
public boolean need_to_upgrade;
}
现在你可以将 BaseResponse<MyResponse>
用作 Retrofit 调用的返回类型。对于数组响应,你也可以做同样的事情,即创建一个 BaseListResponse
类。
英文:
Create a Base Contract and extend it by all of the response classes. in Contract data
part will be Generic.
public class BaseResponse<T> {
public boolean success;
public String message;
public T data;
}
Now you have to create data class for each type of response.
public class MyResponse{
public String update_status;
public String last_version_name;
public String last_version_code;
public boolean need_to_upgrade;
}
Now you can use BaseResponse<MyResponse>
as return type of retrofit call. You can do the same for Array response i.e create a BaseListResponse
class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论