0

我知道这已被问过很多次,但提供的解决方案都不适用于我的情况。

这是我从网络服务收到的 JSON 响应

{
"size": 1,
"_links": {
"context": "XXXX",
"self": "XXXXXX",
"base": "XXXXXX"
},
"start": 0,
"limit": 50,
"results": [
 {
  "container": {
    "extensions": {
      "position": "none"
    },
    "_links": {
      "webui": "XXXX",
      "tinyui": "XXXX",
      "self": "XXXXXX"
    },
    "id": "XXXXX",
    "type": "page",
    "title": "XXXXX",
    "_expandable": {
      "container": "XXXXX",
      "metadata": "",
      "operations": "",
      "children": "XXXX/child",
      "history": "XXXX/history",
      "ancestors": "",
      "body": "",
      "version": "",
      "descendants": "XXXXX/descendant",
      "space": "XXXXX"
    },
    "status": "current"
  },
  "metadata": {
    "mediaType": "text/plain",
    "comment": ""
  },
  "extensions": {
    "fileSize": 8,
    "mediaType": "text/plain",
    "comment": ""
  },
  "_links": {
    "download": "/download/attachments/XXXXX/MyData1.txt?version=1&modificationDate=1483652732000&api=v2",
    "webui": "XXXXX",
    "self": "XXXXX"
  },
  "id": "attXXXXXX",
  "type": "attachment",
  "title": "MyData1.txt",
  "_expandable": {
    "operations": "",
    "children": "XXXX",
    "history": "XXXXX",
    "ancestors": "",
    "body": "",
    "descendants": "XXXXX",
    "space": "XXXXX"
  },
  "version": {
    "number": 1,
    "minorEdit": false,
    "by": {
      "profilePicture": {
        "path": "XXXXX",
        "isDefault": true,
        "width": 48,
        "height": 48
      },
      "displayName": "XXXXX",
      "type": "known",
      "userKey": "XXXXX",
      "username": "XXXXX"
    },
    "message": "",
    "when": "2017-01-05T16:45:32.000-05:00"
  },
  "status": "current"
}
]
}

我需要找到 id 的值 attXXXXXX,这是我的代码。

JSONObject page = new JSONObject(pageObj); 
JSONArray jsonArray= page.getJSONArray("results");

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}

但是上面的循环只运行一次,因为 jsonArray 的长度为 1。其他帖子中提供的所有解决方案都是相同的,即遍历 json 数组。我错过了什么吗?建议 ?

4

2 回答 2

0

您的 JSON 字符串在“结果”对象中只有一个值。所以你的数组大小返回为 1。这是正确的。

如果您期望多个数组,请检查构建 JSON 的服务器端代码。

请参阅下图以了解更多信息。

在此处输入图像描述

我没有测试它。你可以试试这个。如果您有解决方案,请投票。

JSONObject page = new JSONObject(pageObj); 
JSONArray jsonArray= page.getJSONArray("results");

for (int i = 0; i < jsonArray.length(); i++) {
   JSONObject explrObject = jsonArray.getJSONObject(i);
   explrObject.getString("id")
}
于 2017-01-06T02:34:50.007 回答
0

好的,所以我能够使用 Rest Assured API 从响应中获取值。这是一个从 JSON 数组中获取值的简单 API。基本上我必须使用以下命令来获取值

response.path("results.id");
于 2017-01-06T17:55:52.453 回答