创建JSON数组和JSON对象

时间:2018-01-24 09:27:11

标签: java android json xml

我从XML文件中获取数据,这是我解析XML的代码,我没有遇到任何问题。我不熟悉ArrayList所以我坚持使用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();
        }
    }

我正在尝试在此结构中创建一个JSON对象。

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

我已经按照以下示例进行了操作 Android- create JSON Array and JSON Object

1 个答案:

答案 0 :(得分:0)

试试这个

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

<强>输出

enter image description here