Creating JSON in java using org.json

raju picture raju · Apr 29, 2013 · Viewed 12.5k times · Source

I am trying to create a json string in java using org.json library and following is the code snippet.

JSONArray jSONArray = new JSONArray();
JSONObject jSONObject = new JSONObject();
jSONObject.accumulate("test", jSONArray);
System.out.println(jSONObject.toString());

I expected it to print

{"test":[]} 

while it prints

{"test":[[]]}

Answer

thepoosh picture thepoosh · Apr 29, 2013

instead of using accumulate use put this way it won;t add it to a pre-existing (or create and add) JSONArray, but add it as a key to the JSONObject like this:

JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("test", array);
System.out.println(obj.toString());

and now it'll print {"test":[]}