Reputation: 105
I have a problem putting JSONObject into JSONArray.
Here is my code:
String strObject = "{\"Code\":\"a\", \"Name\": \"b\"}";
JSONObject anExistedObject = new JSONObject(strObject);
JSONArray myArray = new JSONArray();
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject;
myObject = anExistedObject;
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());
Result:
[
{
"Code": "a",
"Name": "b",
"Count": 1
},
{
"Code": "a",
"Name": "b",
"Count": 1
}
]
What I expected:
[
{
"Code": "a",
"Name": "b",
"Count": 0
},
{
"Code": "a",
"Name": "b",
"Count": 1
}
]
I've read this post but still don't know how to fix mine. Did I missed something?
Upvotes: 0
Views: 81
Reputation: 11558
You each time modify same object because of line: myObject = anExistedObj;
You need make copy of that object instead.
Correct code:
JSONObject anExistedObj = new JSONObject();
myObject.put("Code", "a");
myObject.put("Name", "a");
JSONArray myArray = new JSONArray();
String[] keys = JSONObject.getNames(anExistedObj);
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject(anExistedObj, keys);
//anExistedObj = {"Code":"a", "Name": "b"}
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());
Checkout documentation of copy constructor JSONObject
Upvotes: 2
Reputation: 3621
This happens because the line myObject.put("Count", count);
always modifies the same object since the variable is only a reference to the object itself. Meaning that myObject
and anExistedObject
point to the same object.
You should create a copy with:
JSONObject copy = new JSONObject(original, JSONObject.getNames(original));
Instead of using:
JSONObject myObject = new JSONObject;
myObject = anExistedObj;
Upvotes: 1
Reputation: 1219
You are updating and reusing anExistedObject everytime
String strObject = "{\"Code\":\"a\", \"Name\": \"b\"}";
JSONArray myArray = new JSONArray();
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject(strObject);
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());
Upvotes: 1