JSON add to JSONArray issue

后端 未结 2 1700
忘了有多久
忘了有多久 2020-12-11 16:11

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 ride

相关标签:
2条回答
  • 2020-12-11 16:58

    Although I created a new JSONObject every time the loop ran, I still had the same problem. so what I did is I created a List of JSONObjects and each time the loop ran I added a new record to my list and update that record each time. At the end in a for-loop, I fed my JSONArray by my list.

    JSONArray jsonArray = new JSONArray();
    List<JSONObject> myList = new ArrayList()<>;
    if(X.size() > 0)
    {
      for (int j = 0; j < X.size(); j++)
      {
        myList.add(new JSONObject());
        zBean aBean = (zBean)X.get(
        myList.get(j).put(ID,newInteger(aBean.getId()));
        myList.get(j).put(NAME,aBean.
      }
      for(int j = 0; j < myList.size(); j++)
        jsonArray.add(myList.get(j));
    }
    
    0 讨论(0)
  • 2020-12-11 17:03

    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.

    0 讨论(0)
提交回复
热议问题