简体   繁体   中英

Getting exception “ at answer of type org.json.JSONObject cannot be converted to JSONArray” while parsing JSON array

I need to segregate question and their answer from the [answer] array in JSON Array "subject_wise_test_ans".

JSONArray temp = response.getJSONArray("subject_wise_test_ans");

                         JSONObject buffer1;
                            for (int i = 0; i < temp.length(); i++) {
                                JSONObject buffer = temp.getJSONObject(i);
                                String id= buffer.getString("id");
                                String test_id= buffer.getString("test_id");
                                String subject_name = buffer.getString("subject_name");
                                JSONArray answer = buffer.getJSONArray("answer");
                                String marks_pluse = buffer.getString("marks_pluse");
                                String marks_minus = buffer.getString("marks_minus");
                                String answer_set = buffer.getString("answer");

                                String answer_key = buffer.getString("answer_key");

                                Log.i("Answer Array 1", answer.toString());

This is JSON output:

    {
   "subject_wise_test_ans":[
      {
         "id":52,
         "test_id":"7",
         "subject_name":"8",
         "question_no":"25",
         "answer":{
            "1":"B",
            "2":"A",
            "3":"B",
            "4":"D",
            "5":"A",
            "6":"D",
            "7":"B",
            "8":"D",
            "9":"A",
            "10":"A",
            "11":"C",
            "12":"C",
            "13":"D",
            "14":"D",
            "15":"D",
            "16":"D",
            "17":"B",
            "18":"B",
            "19":"B",
            "20":"D",
            "21":"A",
            "22":"A",
            "23":"B",
            "24":"D",
            "25":"B"
         },
         "marks_pluse":"2",
         "marks_minus":"0.67",
         "answer_key":"c6840363cdcaca8ca87cc8755f76898c.pdf"
      },
      ...

I'm getting exception:

W/System.err: org.json.JSONException: Value {"1":"B","2":"A","3":"B","4":"D","5":"A","6":"D","7":"B","8":"D","9":"A","10":"A","11":"C","12":"C","13":"D","14":"D","15":"D","16":"D","17":"B","18":"B","19":"B","20":"D","21":"A","22":"A","23":"B","24":"D","25":"B"} 
at answer of type org.json.JSONObject cannot be converted to JSONArray

Replace JSONArray answer = buffer.getJSONArray("answer");

by

JSONObject answer = buffer.getJSONObject("answer");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM