如何将 ArrayLIst 项转换为 Android 中的 json 个对象

How to convert ArrayLIst items into json objects in Android

我有两个数组列表,我想将数组列表的项目转换为 json 个对象,然后将这些 json 个对象添加到数组列表中。

Json 对象和数组

     JSONObject jobj_id=new JSONObject();
     JSONObject jobj_ans=new JSONObject();
     JSONArray qhis_jar=new JSONArray();

将arraylist转换为json的代码

 for(int i=0;i<arr_quesid.size();i++)
     {
         try {

            jobj_id.put("ques_id", arr_quesid.get(i));
            qhis_jar.put(jobj_id);
            jobj_ans.put("ans", arr_ans.get(i));
            qhis_jar.put(jobj_ans);


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

但我只得到 arraylist 的最后一个元素作为 json 个对象。

[{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"}]

请告诉

您可以使用新的 Gson 库...

ArrayList<String> list = new ArrayList<String>();
String jsonData = new Gson().toJson(list);

创建包含其他 JSONObject 的 JSONArray:

for(int i=0;i<arr_quesid.size();i++)
     {      

            jobj_id=new JSONObejct(); // 
            jobj_id.put("ques_id", arr_quesid.get(i));
            qhis_jar.put(jobj_id);
            jobj_ans=new JSONObejct();
            jobj_ans.put("ans", arr_ans.get(i));
            qhis_jar.put(jobj_ans);
     }

因为目前您正在用下一个值覆盖值 jobj_idjobj_ans,这就是为什么 qhis_jar JSONArray 仅包含最后一个值