Reputation: 61
I am trying to create a JsonArray using a loop and adding the loop index to value, but getting last index in the JsonArray.
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
for(int i=0;i<2;i++) {
item.put("information", "test"+i);
item.put("id", 0+i);
item.put("subName", "course"+i);
//System.out.println(item.toString());
array.add(item);
System.out.println(array.toString());
}
Expected result:
[{"subName":"course0","information":"test0","id":0},
{"subName":"course1","information":"test1","id":1}]
Actual result:
[{"subName":"course1","information":"test1","id":1},{"subName":"course1","information":"test1","id":1}]
Upvotes: 1
Views: 137
Reputation: 411
Your code only creates one JSONObject
and then keeps modifying it. The following example illustrates this:
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("id", 0);
array.add(item);
// The next line overwrites the "id" in item. This also affects
// the one already in the array because it's the same instance
item.put("id", 1);
array.add(item);
System.out.println(array.toString());
The array now contains the same instance twice. Result: [{"id":0}, {"id":0}]
JSONArray array = new JSONArray();
JSONObject item1 = new JSONObject();
item1.put("id", 0);
array.add(item1);
JSONObject item2 = new JSONObject();
item2.put("id", 1);
array.add(item2);
System.out.println(array.toString());
The array now contains two distinct instances. Result: [{"id":0}, {"id":1}]
In your code, you can solve the problem by moving the creation of the JSONObject
instances into the loop:
for(int i=0;i<2;i++) {
JSONObject item = new JSONObject(); // moved inside loop
item.put("information", "test"+i);
...
array.add(item); //
Upvotes: 1