Creating nested JSON object for the following structure in Java using JSONObject? [closed]

With the imports org.json.JSONArray and org.json.JSONObject

JSONObject object = new JSONObject();
object.put("name", "sample");
JSONArray array = new JSONArray();

JSONObject arrayElementOne = new JSONObject();
arrayElementOne.put("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();

JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.put("name", "ABC");
arrayElementOneArrayElementOne.put("type", "STRING");

JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.put("name", "XYZ");
arrayElementOneArrayElementTwo.put("type", "STRING");

arrayElementOneArray.put(arrayElementOneArrayElementOne);
arrayElementOneArray.put(arrayElementOneArrayElementTwo);

arrayElementOne.put("setDef", arrayElementOneArray);
array.put(arrayElementOne);
object.put("def", array);

I did not include first array’s second element for clarity. Hope you got the point though.

EDIT:

The previous answer was assuming you were using org.json.JSONObject and org.json.JSONArray.

For net.sf.json.JSONObject and net.sf.json.JSONArray :

JSONObject object = new JSONObject();
object.element("name", "sample");
JSONArray array = new JSONArray();

JSONObject arrayElementOne = new JSONObject();
arrayElementOne.element("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();

JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.element("name", "ABC");
arrayElementOneArrayElementOne.element("type", "STRING");

JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.element("name", "XYZ");
arrayElementOneArrayElementTwo.element("type", "STRING");

arrayElementOneArray.add(arrayElementOneArrayElementOne);
arrayElementOneArray.add(arrayElementOneArrayElementTwo);

arrayElementOne.element("setDef", arrayElementOneArray);
object.element("def", array);

Basically it’s the same, replacing the method ‘put’ for ‘element’ in JSONObject, and ‘put’ for ‘add’ in JSONArray.

Leave a Comment