2017-01-06 110 views
0

我知道這已被問了很多次,但沒有提供的解決方案是在我的情況下工作。如何從JSON數組中獲取字符串值?

這裏是我的JSON這我得到的響應從web服務

{ 
"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" 
} 
] 
} 

我需要找到哪些是attXXXXXX這裏是我的代碼的id的值。

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

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

但上述循環只是運行一次作爲jsonArray的lenght是1.在其他職位中提供的所有溶液都在JSON陣列相同的,即迭代。我錯過了什麼嗎?建議?

+0

它看起來像你正在使用java,但你只用'json'標記你的問題。你能否包含你正在使用的基礎技術和json庫的標籤? –

+0

如果使用php Json解碼將它變成一個普通的php對象。然後,您只需通過它在當時的值來引用它。 – DEVPROCB

+0

添加了更多標籤.. – Naseem

回答

0

您的JSON字符串在「結果」對象中只有一個值。所以你的數組大小返回爲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") 
} 
+0

感謝您使它更加清晰。你有任何解決方案來獲得id值? – Naseem

+0

更新了答案。 Plz檢查。 – GrabNewTech

+0

不...第一次找到id值,第二次找不到id值,因爲jsonArray大小 – Naseem

0

好吧,所以我能夠使用Rest Assured API從響應中獲取值。從JSON數組中獲取值是一個簡單的API。基本上我必須使用下面的命令來獲得值

response.path("results.id");