在我的应用程序中,我从服务器收到响应,其中包含有关收到的信件的所有重要信息。您可以看到此类回复的示例:
{
"count": int, # number of messages
"messages": [ # array of messages
{
"id": int, # message id
"subject": str, # message subject
"can_delete": bool, # can it be deleted (True) or not (False)
"new": int # message already read (0) or not (1)
"date": str, # date of message in 'd.m.y'. If message was sent today format will be 'H:M'
"receiver_name": str, # name of receiver if type=1
"sender_name": str, # name of sender if type=0
}, ...
],
"next_url": URL, # url for get next messages, if no more messages value is null
"previous_url": URL # url for get previous messages, if no more messages value is null
}
据我了解,我必须创建一个包含所有相似字段的类,然后将其用于将以下信息提取到某些适配器中。但是我不明白如何在课堂上编写所有这些字段。我必须用我的响应样本来创建所有类似对象,例如计数或消息数组???我完全不了解创建此数组的方式,因为我看到必须在数组初始化中插入一些数据。
答案 0 :(得分:1)
要执行所需的操作,必须创建具有与响应相同的结构的模型(类)。然后,您可以将其解析为一个对象并轻松处理数据。
您的模型是这样的:
public class MyMessage{
private int id;
private String subject;
private boolean can_delete;
@SerializedName("new") //this is because new is a protected keyword. this annotation is for Gson parsing library. Any library has his own annotation
private int newField;
private String date;
private String receiver_name;
private String sender_name;
public MyMessage(){}
//here getters and setters
}
public class ResponseMessage{
private int count;
private List<MyMessage> messages;
private String next_url;
private String previous_url;
public ResponseMessage() {
}
//here getters and setters
}
注意:您需要用于json解析的类是ResponseMessage
。
请注意,new
字段的关键字存在一些问题。您将需要以其他方式调用它并指定该属性的serializedName
。
希望这会有所帮助
您的情况的简单用法是:
Gson gson = new GsonBuilder().create();
ResponseMessage myWebResponse = gson.fromJson(inputString, ResponseMessage.class);
其中ResponseMessage
是反序列化的对象,而inputString
是您的json字符串:)