2017-04-10 550 views
0

我有一个名为childData的JSONObject,它包含每个项目的名称,数量和价格,并将其添加到JSONArray pa中。但是在每次迭代之后,先前迭代的childData输出值将被pa中当前迭代输出值的值替换。在JSONArray中复制的JSONObject数据

代码:

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); 
    } 

正在生产输出像下面

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

您需要在创建的childData一个新实例循环。事情是这样的:

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); 
} 

你现在正在做的方式,还有这是你把数组中的元素之间共享一个单一的childData实例。修改该实例时,它也会对每个元素进行“修改”。所以,当它序列化它时,你会看到你看到的不好的结果。