-7

I'm getting data from an XML file and this is my code for parsing the XML, which I have no problems with. I'm not familiar with ArrayList so I stick with JSON.

while (eventType != XmlPullParser.END_DOCUMENT)
    {
        if(eventType == XmlPullParser.START_DOCUMENT)
        {
            Log.e("XML READ","--- Start XML ---");
        }
        else if(eventType == XmlPullParser.START_TAG) {
            if (xpp.getName().toString().equals("question")) {

            } else if (xpp.getName().toString().equals("choice")) {
                try {
                    choices = new JSONObject();
                    choices.put("value", xpp.getAttributeValue(null, "value"));
                    choices.put("iscorrect", xpp.getAttributeValue(null, "iscorrect"));
                    jsonArray.put(choices);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        try {
            questions.put("questions", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            eventType = xpp.next();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

I'm trying to create a JSON Object in this structure.

{
    "question": [
        {
            "q": "what is 1 + 1?",
            "choices": [
                {
                    "ans":"1",
                    "iscorrect":"false"
                },
                {
                    "ans":"2",
                    "iscorrect":"true"
                }
            ]
        },
    ]
}

I have followed below example for code Android- create JSON Array and JSON Object

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
addykha
  • 61
  • 1
  • 11

1 Answers1

0

Try this

JSONObject jsonObjque1 = new JSONObject();
JSONObject jsonObjque2 = new JSONObject();

try 
{
     jsonObjque1.put("ans", "1");
     jsonObjque1.put("iscorrect", "false");

     jsonObjque2.put("ans", "2");
     jsonObjque2.put("iscorrect", "true");

} catch (JSONException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

 JSONArray jsonArrayChoice = new JSONArray();

 jsonArrayChoice.put(jsonObjque1);
 jsonArrayChoice.put(jsonObjque2);

 JSONObject ChoiceObj = new JSONObject();
 ChoiceObj.put("q", "what is 1 + 1?");
 ChoiceObj.put("choices", jsonArrayChoice);


 JSONArray jsonArrayquestion = new JSONArray();

 jsonArrayquestion.put(ChoiceObj);

 JSONObject jsonObjectMain = new JSONObject();

 jsonObjectMain.put("question", jsonArrayquestion);

 Log.i("TAG", "JSON Response :" + jsonObjectMain.toString());

OUTPUT

enter image description here

Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31