Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

java - JSON add to JSONArray issue

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...