2017-09-26 32 views
-4

我有這樣的代碼,的jArrAnswer值是機器人JSONException索引1超出範圍[0..1](解析1個內循環2個JSON陣列)

[{"answer":"Yes"},{"answer":"No"},{"answer":"maybe"},{"answer":"yrg"}] 

jArrAnswer.length()結果4

但爲什麼我得到錯誤

org.json.JSONException:指數1超出範圍[0..1)。

try { 
     JSONArray jArrAnswerid = new JSONArray(answerid); 
     JSONArray jArrAnswer = new JSONArray(answer); 
     for (int i = 0; i < jArrAnswer.length(); i++) { 
      JSONObject jObjAnswerid = jArrAnswerid.getJSONObject(i); 
      JSONObject jObjAnswer = jArrAnswer.getJSONObject(i); 
      String ansid = jObjAnswerid.getString("answerid"); 
      String ans= jObjAnswer.getString("answer"); 
      GroupModel item2 = new GroupModel(String.valueOf(i + 1), ans, ansid); 
     } 
} catch (Exception e) { 
     Log.w("asdf", e.toString()); 
} 
+0

能否請您發表您的JSON響應? –

+1

什麼是'jArrAnswerid.length()'? –

+0

檢查我的編輯職位 – Lukmanpryg

回答

3

您在jArrAnswer迭代for loop,而你的抓取索引i超過jArrAnswerid

檢查並確保jArrAnswerid.size()等於jArrAnswer.size()

打印jArrAnswerid.size()並檢查。

+0

好吧,等一下,我會檢查一下 – Lukmanpryg

+0

感謝兄弟,jArrAsnwerid.length的值不同於jArrAnswer.length – Lukmanpryg

+0

很高興工作。 – iMDroid

1

試試這個

try { 
     JSONArray jArrAnswer = new JSONArray(answer); 
     for (int i = 0; i < jArrAnswer.length(); i++) { 
      JSONObject jObjAnswer = jArrAnswer.getJSONObject(i); 
      String ansid = jObjAnswer.getString("answerid"); 
      String ans= jObjAnswer.getString("answer"); 
     } 
    } catch (Exception e) { 
     Log.w("asdf", e.toString()); 
    } 

提供 「答案」 是你的JSON陣列響應

+0

我從一開始就一直在思考這個問題,但我的需求是不同的。所以我做了2個json數組 – Lukmanpryg

0

嘗試

String json = "[{\"answer\":\"Yes\",\"answerid\":\"1\"},{\"answer\":\"No\",\"answerid\":\"2\"},{\"answer\":\"maybe\",\"answerid\":\"3\"},{\"answer\":\"yrg\",\"answerid\":\"4\"}]"; 

try { 
    JSONArray jsonArray = new JSONArray(json); 
    if(jsonArray != null) { 
     for (int i = 0; i < jsonArray.length(); i++) { 
      JSONObject jsonObject = jsonArray.getJSONObject(i); 
      String answerId = jsonObject.getString("answerid"); 
      String answer = jsonObject.getString("answer"); 
      //Use answerId and answer 
     } 
    } 
} catch(JSONException e) { 
    e.printStackTrace(); 
} 
相關問題