2017-09-25 59 views
-3

我試圖從JSONObject中提取數據時出現上述錯誤。我的目標是提取「transactionId」數據並將其存儲在變量中以供將來使用。JsonObject中的getJsonObject無法應用於int

我有什麼至今:

protected void onPostExecute(String result) { 

     super.onPostExecute(result); 
     if (pd.isShowing()) { 
      pd.dismiss(); 
     } 
     /*txtJson.setText(result);*/ 


     JSONObject jsonarray; 
     try { 
      jsonarray = new JSONObject(result); 
      for (int i = 0; i < jsonarray.length(); i++) { 
       JSONObject mJsonObject = jsonarray.getJSONObject(i); 
       Log.d("OutPut", mJsonObject.getString("transactionId")); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
} 

我的JSON對象如下圖所示:

{ 
"merchantId":"X", 
"transactionId":"Y" 
} 

我是新來編程,因此任何幫助,將不勝感激。

+1

'的JSONObject jsonarray'什麼是思維過程嗎? –

+2

[如何在Android中解析JSON]可能的重複(https://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) –

+0

不需要'for循環',如果只使用JSON有單個對象 –

回答

0

試試這個代碼

JSONArray jsonarray; 
    try { 
     jsonarray = new JSONArray(result); 
     for (int i = 0; i < jsonarray.length(); i++) { 
      JSONObject mJsonObject = jsonarray.optJSONObject(i); 
      Log.d("OutPut", mJsonObject.optString("transactionId")); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

而且,如果單個項目在JSONArray,您可以刪除for循環。

而且,如果接收到的響應是JSONObject的話,

JSONObject jsonObject; 
    try { 
     jsonObject = new JSONObject(result); 
     Log.d("OutPut", jsonObject.optString("transactionId")); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
+0

謝謝你的回答。使用JsonObject部件,Android Device Monitor不會顯示任何錯誤/警告,但也不會記錄OutPut。 –

+0

嘗試調試並檢查爲什麼不顯示任何日誌 – Meenal

相關問題