我正在编写一个 native Android 应用程序,我在其中使用 PHP MYSQL 使用 GET 请求从服务器获取数据。 服务器向我发送结果的方式如下:
{
"result": true,
"error_message": "",
"response": [
{
"total_tasks": 8,
"tasks": [
{
"id": 8,
"name": "Hello Christine, call Mr. Dejan Mandic"
},
{
"id": 7,
"name": "Hello Christine, call Ms. Charente Douglas-Smith"
},
{
"id": 6,
"name": "Hello Christine, call Mrs. Alison Marshall"
},
{
"id": 5,
"name": "Hello Christine, call Mrs. Muna Crisp"
},
{
"id": 4,
"name": "Hello Christine, call Mr. Victor Crisp"
},
{
"id": 3,
"name": "Hello Christine, call Mrs. Kathy Dunn"
},
{
"id": 2,
"name": "Hello Christine, call Mr. Peter Dunn"
},
{
"id": 1,
"name": "Hello Christine, call Ms. Vanessa Allen"
}
]
}
]
我需要在我的 Android ListView 中显示数组“respones”->“tasks”(即 id 和名称)中的数据,最终当用户单击 ListView 中的特定行时,有关该任务的信息是使用 id 在另一个 Activity 中显示。由于服务器以多维数组的形式发送数据,因此我在获取 ListView 中的数据时遇到了问题。 如果有人可以帮助我,那将是一个很大的帮助。 谢谢:)
最佳答案
JSONObject responseObject = new JSONObject(responseString);
boolean resultSuccess = responseObject.getBoolean("result");
if(resultSuccess) {
JSONArray responseArray = responseObject.getJSONArray("response");
JSONObject firstResponse = responseArray.getJSONObject(0);
JSONArray tasks = firstResponse.getJSONArray("tasks");
for(int i = 0; i < tasks.length(); i++){
JSONObject task = tasks.getJSONObject(i);
int id = task.getInt("id");
String name= task.getString("name");
}
}
尽管我对你的 JSON 树有一些评论,但你只需要浏览树来解析你的 json
- 为什么将响应作为数组?这只是一个对象 对吧?
- 任务的数量是冗余数据,您已经拥有任务并可以从中推断出长度。
关于android - 如何在发送多维数组的服务器的 Android ListView 中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30112921/