JSON添加到JSONArray问题 [英] JSON add to JSONArray issue
问题描述
我不是Json最好的.我试图通过循环将一些json对象添加到json数组中,但是问题是每次涉及到循环时,它也会通过新数据来遍历数组中的先前数据.这是我的代码:
Hi All I am not the best at Json. I was trying to add some json object into a json array through a loop, but the problem is everytime it comes to the loop, it also over rides the previous data in the array by the new data. here is my code:
JSONObject jsonObj = new JSONObject();
JSONArray jsonArray = new JSONArray();
if(X.size() > 0)
{
for (int j = 0; j < X.size(); j++)
{
zBean aBean = (zBean)X.get(j);
jsonObj.put(ID,newInteger(aBean.getId()));
jsonObj.put(NAME,aBean.getName());
jsonArray.add(jsonObj);
}
}
给出X.size = 2的示例:
example given X.size = 2:
when j=0
jsonObj => {"Name":"name1","Id":1000}
jsonArray => [{"Name":"name1","Id":1000}]
when j = 1
jsonObj => {"Name":"name2","Id":1001}
jsonArray => [{"Name":"name2","Id":1001},{"Name":"name2","Id":1001}]
我希望我的例子足够清楚.
I hope my example is clear enough.
如果有人可以在这里帮助我,我将不胜感激.
Id be grateful if anyone can help me here.
推荐答案
您需要在循环的每次迭代中创建一个新的jsonObj
引用:
You need to create a new jsonObj
reference with every iteration of the loop:
for (int j = 0; j < X.size(); j++)
{
zBean aBean = (zBean)X.get(j);
jsonObj = new JSONObject();
//^^^^^^^^^^^^^^^^^^^^^^^^^^^ add this line
jsonObj.put(ID,newInteger(aBean.getId()));
jsonObj.put(NAME,aBean.getName());
jsonArray.add(jsonObj);
}
否则,您将一遍又一遍地更新同一实例,并将对同一对象的引用多次添加到数组中.由于它们都是相同的引用,因此对其中一个的更改会影响数组中的所有它们.
Otherwise you are updating the same instance over and over again, and adding a reference to the same object many times to the array. Since they are all the same reference, a change to one of them affects all of them in the array.
这篇关于JSON添加到JSONArray问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!