android JSONException index 1 out of range [0..1] (Parse 2 json arrays inside 1 loop)

心不动则不痛 提交于 2019-12-12 07:03:25

问题


I have code like this, the value of jArrAnswer is

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

the result from jArrAnswer.length() is 4

but why I got error

org.json.JSONException: Index 1 out of range [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());
}

回答1:


You are iterating the for loop over jArrAnswer while your fetching the index i over jArrAnswerid.

Check and make sure that the jArrAnswerid.size() is equal to the jArrAnswer.size().

Print the jArrAnswerid.size() and check.




回答2:


Try this

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());
     }

provided "answer" is your json array response




回答3:


Try

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();
}


来源:https://stackoverflow.com/questions/46418094/android-jsonexception-index-1-out-of-range-0-1-parse-2-json-arrays-inside-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!