Sumi
Sumi

Reputation: 157

JSONObject data duplicating in JSONArray

I ve JSONObject named childData which contains name, quantity and price of each item and it is added in JSONArray pa. But after each iteration previous iteration output value of childData is getting replaced by the value of current iteration output value in pa.

Code:

    JSONArray pa = new JSONArray();
    JSONObject childData = new JSONObject();
    for(int i=0; i<name.size();i++) {
        childData.put("Name", name.get(i));
        childData.put("Qty", qty.get(i));
        childData.put("Amt", price.get(i));
        pa.put(childData);
    }

is producing the output like below

    childData= {"Name":"Shirt","Qty":"1","Amt":"300"}
    pa= [{"Name":"Shirt","Qty":"1","Amt":"300"}]
    child= {"Name":"Coat","Qty":"1","Amt":"210"}
    pa= [{"Name":"Coat","Qty":"1","Amt":"210"},{"Name":"Coat","Qty":"1","Amt":"210"}]

Upvotes: 0

Views: 25

Answers (1)

Horia Coman
Horia Coman

Reputation: 8781

You need to create a new instance of childData in the for loop. Something like this:

JSONArray pa = new JSONArray();
for(int i=0; i<name.size();i++) {
    JSONObject childData = new JSONObject();
    childData.put("Name", name.get(i));
    childData.put("Qty", qty.get(i));
    childData.put("Amt", price.get(i));
    pa.put(childData);
}

The way you're doing it now, there is a single childData instance which is shared among all the elements you put in the array. When you modify that instance, it gets "modified" for every element as well. So when it comes time to serialize it, you get the bad results you see.

Upvotes: 1

Related Questions