如何从JSON数组中获取String值?

时间:2017-01-06 02:08:44

标签: json httpresponse apache-httpclient-4.x http-get httpentity

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

这是我的JSON,我作为webservice的回复

{
"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数组。我错过了什么吗?建议?

2 个答案:

答案 0 :(得分:0)

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

如果您需要多个阵列,请检查构建JSON的服务器端代码。

有关更多说明,请参阅下图。

enter image description here

我没有测试过它。你能试试这个吗?如果你得到解决方案,请投票。

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")
}

答案 1 :(得分:0)

好的,我可以使用Rest Assured API从响应中获取值。这是从JSON Array获取值的简单API。基本上我必须使用以下命令来获取值

response.path("results.id");