user6456773 user6456773 - 1 year ago 104
JSON Question

JSON object building

Currently I have this JSON structure:


What I need to achieve is this:

{"title4":[{"a":"aa","b": "bb"}]}

To achieve the above, I use JSONArray:

JSONArray list = new JSONArray();
obj.put("title1", list);

And JSONObject:

JSONObject obj = new JSONObject();
obj.put("title2", "info2");

How can I visualize the desired output?

Answer Source

To achieve what you want, a JSONObject with a JSONArray containing JSONObjects, you can use the following code

JSONObject root = new JSONObject(); // The root JSON object

JSONArray title4 = new JSONArray(); // The JSON array that will contain JSON objects

// The JSON objects
JSONObject a = new JSONObject();
a.put("a", "aa");

JSONObject b = new JSONObject();
b.put("b", "bb");

// Put the JSON array in the root JSON object
root.put("title4", title4);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download