0

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"}]

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.