【问题标题】:Create JSON Array and JSON Object创建 JSON 数组和 JSON 对象
【发布时间】:2018-07-03 06:54:19
【问题描述】:

我从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

【问题讨论】:

  • 那么你的问题是什么?
  • @addykha 请检查我的答案。

标签: java android json xml


【解决方案1】:

试试这个

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

输出

【讨论】:

  • 只有在jsonObjque1不在循环中时才有效
猜你喜欢
  • 2013-07-22
  • 2013-08-28
  • 1970-01-01
  • 2022-01-19
  • 2021-09-22
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
相关资源
最近更新 更多