2017-08-20 75 views
0

我試圖從「當前」數組中拉出「價格」對象,我已經好幾個小時了,現在沒有運氣,任何幫助表示讚賞! :)從JSONArray中拉JSONObject?

try { 
      URL url = new URL("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=2"); 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
      try { 
       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
       StringBuilder stringBuilder = new StringBuilder(); 
       String line; 
       while ((line = bufferedReader.readLine()) != null) { 
        stringBuilder.append(line).append("\n"); 
       } 
       bufferedReader.close(); 
       return stringBuilder.toString(); 
      } finally { 
       JSONArray nu1 = jobj.getJSONArray("current"); 
       JSONObject jobj = nu1.getJSONObject(0); 
       String price = jobj.getString("price"); 
       Toast.makeText(getApplicationContext(), price, Toast.LENGTH_SHORT).show(); 
      } 

     } catch (Exception e) { 
      Log.e("ERROR", e.getMessage(), e); 
      return null; 
     } 
    } 

    protected void onPostExecute(String response) { 

    } 
} 

}

+0

歡迎來到Stack Overflow。請閱讀https://stackoverflow.com/help/how-to-ask關於如何提出一個好問題。你試過什麼了?數據是什麼樣子的,你試圖提取哪些元素?你是否有控制檯錯誤?我認爲你第一次使用'jobj'是未定義的。 – Mikkel

回答

1

我試圖從你的URL響應。這裏是迴應:

{ 
"item": { 
    "icon": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_sprite.gif?id=2", 
    "icon_large": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_big.gif?id=2", 
    "id": 2, 
    "type": "Ammo", 
    "typeIcon": "http://www.runescape.com/img/categories/Ammo", 
    "name": "Cannonball", 
    "description": "Ammo for the Dwarf Cannon.", 
    "current": { 
     "trend": "neutral", 
     "price": 339 
    }, 
    "today": { 
     "trend": "positive", 
     "price": "+1" 
    }, 
    "members": "true", 
    "day30": { 
     "trend": "positive", 
     "change": "+1.0%" 
    }, 
    "day90": { 
     "trend": "negative", 
     "change": "-11.0%" 
    }, 
    "day180": { 
     "trend": "negative", 
     "change": "-21.0%" 
    } 
} 
} 

響應中沒有數組。

編輯:

假設你存儲在一個名爲response字符串你的迴應,你可以得到的價格,使用下面的代碼:

 JSONObject json = new JSONObject(response); 
     JSONObject item = json.getJSONObject("item"); 
     JSONObject current = item.getJSONObject("current"); 
     int price = current.getInt("price"); 

EDIT2:使用

String response = stringBuilder.toString(); 

和然後從'響應'中創建一個JSONObject。

+0

好吧,那麼如何獲得「價格」:339部分出現?我仍然沒有比以前更接近:( –

+0

@ElyJenkins請檢查我編輯的答案 –

+0

對不起,我是新來的這個東西,只有我的第二天哈哈:)我很享受它,只是渴望得到事情工作,感謝您的答案。我沒有一個名爲響應的字符串,我正在編輯我在網上找到的一段代碼以適合我的需求,任何幫助都將不勝感激:D –