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.
Answer from mellamokb on Stack OverflowYou 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.
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>
Videos
I think it is a problem(aka. bug) with the API you are using. JSONArray implements Collection (the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject has an overloaded put() method which takes a Collection and wraps it in a JSONArray (thus causing the problem). I think you need to force the other JSONObject.put() method to be used:
jsonObject.put("aoColumnDefs",(Object)arr);
You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection) method is broken.
here is simple code
List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("result", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
Hope this helps :)
JSONArray jsonArray = new JSONArray();
for (loop) {
JSONObject jsonObj= new JSONObject();
jsonObj.put("srcOfPhoto", srcOfPhoto);
jsonObj.put("username", "name"+count);
jsonObj.put("userid", "userid"+count);
jsonArray.put(jsonObj.valueToString());
}
JSONObject parameters = new JSONObject();
parameters.put("action", "remove");
parameters.put("datatable", jsonArray );
parameters.put(Constant.MSG_TYPE , Constant.SUCCESS);
Why were you using an Hashmap if what you wanted was to put it into a JSONObject?
EDIT: As per http://www.json.org/javadoc/org/json/JSONArray.html
EDIT2: On the JSONObject method used, I'm following the code available at: https://github.com/stleary/JSON-java/blob/master/JSONObject.java#L2327 , that method is not deprecated.
We're storing a string representation of the JSONObject, not the JSONObject itself
JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());
This works for me.
You can try this:
public static void main(String[] args) throws ParseException {
String jsonString = "{\"a\": \"b\",\"features\": [{\"feature1\": \"value1\"}, {\"feature2\": \"value2\"}]}";
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(jsonString);
JSONObject newJSON = new JSONObject();
newJSON.put("feature3", "value3");
appendToList(jsonObj, newJSON);
System.out.println(jsonObj);
}
private static void appendToList(JSONObject jsonObj, JSONObject toBeAppended) {
JSONArray arr = (JSONArray) jsonObj.get("features");
arr.add(toBeAppended);
}
This will fulfill your both requirements.
Getting the array by: jsonObj["features"], then you can add new item by assign it as the last element in the array ( jsonObj["features"].length is the next free place to add new element)
jsonObj["features"][jsonObj["features"].length] = toBeAppended;
fiddle example
I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object
Here's code to add multiple JSONObjects to JSONArray.
JSONArray Obj = new JSONArray();
try {
for(int i = 0; i < 3; i++) {
// 1st object
JSONObject list1 = new JSONObject();
list1.put("val1",i+1);
list1.put("val2",i+2);
list1.put("val3",i+3);
obj.put(list1);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();
Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.
Something like this maybe:
jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);
Then create new JSONObject, put the other values into it and add it to the JSONArray:
jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);
You can do this way:
JSONArray jRootArray = new JSONArray();
for (int i = 1; i <= 20; i++) {
JSONObject jInnerObject = new JSONObject();
try {
jInnerObject.put(String.valueOf(i), "Hello "+i);
} catch (JSONException e) {
e.printStackTrace();
}
jRootArray.put(jInnerObject);
}
Log.i("JRootArray", jRootArray.toString());
Hope this will help you.
Try this:
private Map<String, String> itemselected = new HashMap<>();
private void selectedItems() {
JSONArray itemSelectedJson = new JSONArray();
// Retrieve all keys
Set<String> keys = itemselected.keySet();
// Add items to JSONArray as JSONObjects
for(String key : keys) {
itemSelectedJson.put(
new JSONObject().put(key, itemselected.get(key))
);
}
}
This way, you won't have to pass by an ArrayList to fill your JSONArray. Then, you can get your JSON string simply by calling the toString() method on the JSON array:
String jsonString = itemSelectedJson.toString();