2015-07-11 101 views
0

我知道如何解析看起來像[{...},{...},{...}]的JSON。但這裏是我的例子,有些不同:android-解析沒有顯式JSONObject的JSONArray

[{"type":"sometype","presentations":["/files/presentation/presentation.pdf"],"description":"somedescription"},{"type":"sometype","presentations":["/files/presentation/presentation2.pdf"],"description":"somedescription"}] 

如何解析來自「演示文稿」的數據?我得到它作爲JSONArray,但不能得到一個值(使用.toString()與該數組返回該值,但與「/」之前「/」(我的意思是「/文件/演示文稿...」) ,所以我不能把它添加到URL來顯示PDF我不知道如何從陣列獲取的JSONObject(如果存在的話,當然)

+0

你已經嘗試過了嗎,你可以發佈你正在解析的代碼嗎? – Pankaj

+0

我可以用它來複制粘貼它,但是後來用自然語言來說,我把這個字符串轉換成JSONArray,然後從它的數組中提取JSONObject號碼,然後做.getString(「演示文稿」),然後將其轉換爲JSONArray(因爲它應該是數組,對吧?)。此外,我做了幾件事情:1)我認爲這是一個隱式的JSONObject,所以我試圖通過數字0獲得jSONObject,然後將其轉換爲字符串,但我記得我甚至無法獲得Object。 2)我試圖轉換爲字符串JSONArray本身希望不使用[]和substring後綴(「\ /」)如上所述 –

+0

首先,你可以檢查從服務器響應你的json是有幾個網站[第一鏈接](http://jsonformatter.curiousconcept.com/)[第二鏈接](http://json.parser.online.fr/)。你可以在這裏檢查你的json是否正確,你可以清楚地看到哪個是正常的字段或對象或數組。 – Pankaj

回答

0
String jsonString = "[{\"type\":\"sometype\",\"presentations\":[\"/files/presentation/presentation.pdf\"],\"description\":\"somedescription\"},{\"type\":\"sometype\",\"presentations\":[\"/files/presentation/presentation2.pdf\"],\"description\":\"somedescription\"}]"; 

try { 
    JSONArray jaArray = new JSONArray(jsonString); 
    JSONObject firstElement = jaArray.getJSONObject(0); 
    JSONArray jaPresentations = firstElement.getJSONArray("presentations"); 
    String string = jaPresentations.getString(0); 

    //or chain it together like so: 
    String string2 = jaArray.getJSONObject(1).getJSONArray("presentations").getString(0); 

    Log.v("TAG", string); 
    Log.v("TAG", string2); 

輸出:。

V/TAG﹕ /files/presentation/presentation.pdf 
V/TAG﹕ /files/presentation/presentation2.pdf