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

前端 未结 3 1869
失恋的感觉
失恋的感觉 2021-01-29 10:24

I have code like this, the value of jArrAnswer is

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

3条回答
  •  野的像风
    2021-01-29 11:10

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

提交回复
热议问题