首页 > 解决方案 > 对象数组

问题描述

对于 android 中的 post 方法,我必须发送对象数组。我正在从 arrayList 中检索元素并将检索到的元素放入 JSONObject 中,而不是将其放入 JSONArray 中的 JSONobject 中。

JSONArray ccArray = new JSONArray();
{
    JSONObject object = new JSONObject();
    if (ccArrayList.size() != 0) {
        for (int i = 0; i < ccArrayList.size(); i++) {
            object.put("emailId", ccArrayList.get(i));
            ccArray.put(object);
        }
    } else {
        object.put("", "");
    }
}

当 arraylist 中有超过 2 个或超过 2 个元素时,它会将 ccrray 中的最后一个元素添加的次数与它们在列表中的元素一样多。

输出 : "cc":[{"emailId":"f@j.com"},{"emailId":"f@j.com"}]

标签: androidjsonarraylist

解决方案


像这样更改代码

 JSONObject obj = new JSONObject();
    JSONArray ccArray = new JSONArray();

                for (int i = 0; i < ccArrayList.size(); i++) {
                    JSONObject object = new JSONObject();
                    if (ccArrayList.size() != 0) {

                        object.put("emailId", ccArrayList.get(i));
                        ccArray.put(object);

                    } else {
                        object.put("", "");
                    }
                }
            obj.put("cc",ccArray);

推荐阅读