0

请帮我。我试图从arraylist的值中将值放在我的json数组上,但不幸的是,我不知道为什么,我的json数组只获取arraylist的最后一个值。我期望输出

[{"Id":"1"},{"Id":"2"},{"Id":"3"}]

但它给了我

[{"Id":"3"},{"Id":"3"},{"Id":"3"}]

你能帮我摆脱困境吗?在此先感谢,这是我的代码:

try

    {
        JSONObject jObject = new JSONObject();
        JSONObject brand = new JSONObject();
        JSONObject consumerSegments = new JSONObject();
        JSONArray jArrayReportUpload = new JSONArray();

        try {
            JSONArray jArraySubrands = new JSONArray();
            JSONArray jArrayConsumerSegments = new JSONArray();

            for (int i = 0; i < arraylist_SUBBRANDS.size(); i++) 
            {
                brand.put("Id", _brands.get(i));
                Log.d("Brand: " + i, _brands.get(i));
                jArraySubrands.put(brand);
            }
            Log.d("JSONbrand", jArraySubrands.toString());

            for (int j = 0; j < arraylist_SEGMENTS.size(); j++) {
                consumerSegments.put("Id",_segments.get(j));
                Log.d("Segment: " + j, _segments.get(j));
                jArrayConsumerSegments.put(consumerSegments);
            }
            Log.d("JSONsegment", jArrayConsumerSegments.toString());
4

1 回答 1

0

JSONObject consumerSegments = new JSONObject();

作为里面的第一条语句

for (int j = 0; j < arraylist_SEGMENTS.size(); j++) {

而不是它当前所在的位置,您只是用相同的值覆盖一个内存块,而不是创建一个新实例来每次都保存新值

于 2013-08-05T02:03:44.510 回答