user6456773 user6456773 - 1 month ago 15
JSON Question

JSON object building

Currently I have this JSON structure:

{"title1":["info1","info2"],"title2":"info2","title3":"info3"}


What I need to achieve is this:

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


To achieve the above, I use JSONArray:

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


And JSONObject:

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


How can I visualize the desired output?

Answer

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");
title4.put(a);
title4.put(b);

// Put the JSON array in the root JSON object
root.put("title4", title4);
Comments