android - 如何将来自服务器的所有响应插入到明确的答案类别中?
问题描述
在我的应用程序中,我收到来自服务器的响应,其中包含有关我收到的信件的所有重要信息。您可以查看此类响应的示例:
{
"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
}
据我了解,我必须创建一个包含所有类似字段的类,然后我将使用它来将以下信息获取到一些适配器中。但我不明白我必须如何在课堂上编写这些所有字段。我必须创建与我的响应样本类似的所有内容,例如计数或消息数组???我根本无法理解创建这个数组的方式,因为我看到我必须在我的数组初始化中插入一些数据。
感谢您的积极回答和建议。
解决方案
要执行您需要的操作,您必须创建一个与响应结构相同的模型(类)。然后您可以将其解析为一个对象并轻松处理数据。
你的模型是这样的:
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 解析的类就是 obv 类ResponseMessage
。
请注意,该new
字段的关键字存在一些问题。您将需要以另一种方式调用它并指定该serializedName
属性的。
希望这可以帮助
编辑:我建议使用Gson。它非常直观和容易。
您的案例的一个简单用法是:
Gson gson = new GsonBuilder().create();
ResponseMessage myWebResponse = gson.fromJson(inputString, ResponseMessage.class);
ResponseMessage
你的反序列化对象在哪里,inputString
你的 json 字符串在哪里 :)
推荐阅读
- java - Java中的XML大写元素值
- file - 使用 SQR 访问另一台计算机上的文件
- google-cloud-storage - 在谷歌云上托管网站的问题
- pandas - 是否可以在 pandas 数据框中执行相当于 SQL 嵌套请求的操作?
- php - 如何在 WordPress 帖子中更改 h2、h3、h4 的颜色
- android - Android 片段高度
- java - 使用 Eclipse 手动导出 EAR 文件
- regex - 计算 sed 中的字符串长度
- c - 如何在 Linux 中获取显示设备名称
- symfony - 为什么当我运行 phpunit 时在测试环境中构建 symfony 容器,而 .env 将 APP_ENV 定义为 dev?