英文:
How can i make a model for this Json file for Retrofit?
问题
Json 文件如下:
{
"data": [
{
"name": "key",
"error": "key 不合法"
},
{
"name": "package_name",
"error": "包名不合法"
}
],
"success": false,
"message": "信息不合法"
}
我有一个 BaseModel,它包含了 "success"、"message"、"data" 这些字段,所有的响应都是从这个类继承的。但是 "data" 对于服务器的每个响应都是不同的。
我目前已经做了如下内容:
public class BaseModel {
private Object data;
private boolean success;
private String message;
}
在这种错误情况下,"data" 将会被转换为一个 DataError 数组:
public class DataError {
private String name;
private String error;
}
然而,我得到了一个错误,错误信息为:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap 无法转换为 com.example.mapp.Model.DataError
我尝试将响应的 "data" 转换为以下的 List:
List<DataError> dataError = (List<DataError>) response.body().getData();
textView.append("错误:" + dataError.get(0).getError());
英文:
The Json file is:
{
"data": [
{
"name": "key",
"error": "key is not valid"
},
{
"name": "package_name",
"error": "package name is not valid"
}
],
"success": false,
"message": "information is not valid"
}
I've got a BaseModel which has "success","message", "data" and all of my responds are extended from this Class.
But "data is different for each response from the server.
I've made this so far:
public class BaseModel{
private Object data;
private boolean success;
private String message;
}
which data for this case of error will cast to an array of DataError:
public class DataError{
private String name;
private String error;
}
And i get an error which tells me :
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.example.mapp.Model.DataError
List<DataError> dataError = (List<DataError>)response.body().getData();
textView.append("Error:"+ dataError.get(0).getError());
答案1
得分: 0
你在解析时需要一个 List<DataError>
,尽管它也可以解析为一个 Map
。在 BaseModel
泛型中创建 data
,这样你可以在其他类中重用它。将其命名为 BaseListModel
,因为它返回一个列表。
public class BaseListModel<T>{
private List<T> data;
private boolean success;
private String message;
}
现在你可以使 API 调用返回 BaseListModel<DataError>
。
对于解析对象类型的响应,你可以创建另一个基础类。
public class BaseModel<T>{
private T data;
private boolean success;
private String message;
}
英文:
You need to have a List<DataError
> when parsing, Although it can also parse as a Map
. Create data
in BaseModel
Generic this way you can reuse it other classes as well. naming it to BaseListModel
cause it return a list.
public class BaseListModel<T>{
private List<T> data;
private boolean success;
private String message;
}
Now you can make the API call return BaseListModel<DataError>
.
For parsing Object type responses you can create other base class .
public class BaseModel<T>{
private T data;
private boolean success;
private String message;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论