JSON add to JSONArray issue

Following will add json obj into json array

public static void main(String[] args) {
    JSONArray jsonArray = new JSONArray();
    int i = 0;
    while(i < 3)
    {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("Name","Random"+i);
        jsonObj.put("ID", i);
        jsonArray.put(jsonObj); //jsonObj will be pushed into jsonArray
        i++;
    }
    System.out.println("jsonArray : "+ jsonArray);
}

Output:

jsonArray : [{"ID":0,"Name":"Random0"},{"ID":1,"Name":"Random1"},{"ID":2,"Name":"Random2"}]

.pom has following dependency

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180813</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.6</version>
    </dependency>
</dependencies>

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.

Tags:

Java

Json