Mr. White Mr. White - 1 year ago 91
JSON Question

How to create multiple JSON objects via for loop

I need to create variable amount of JSON objects and JSON arrays based on the result set from a database query. The JSON format looks very similar to the following which is used for a google chart.

“cols”: [
“rows”: [

My question is, and I feel as though this should be a simple answer, how do I create multiple JSON objects with unique names in a for loop? My attempt:

for(int i=0;i<10;i++) {
JSONObject "tempName"+i = new JSONObject();

Answer Source

Java variable names cannot be constructed dynamically.

I don't know how no one has answered this yet but here you are.

JSONObject objects = new JSONObject[10];
for(int i = 0 ; i < objects.length ; i++) {
    objects[i] = new JSONObject();

JSONObject o = objects[2]; // get the third one

Arrays are not dynamically resizable. You should use an appropriate List implementation if you need such behavior. If you want to access the elements by name, you can also use a Map.

Map<String, JSONObject> map = new HashMap<>();
for(int i = 0 ; i < 10 ; i++) {
    map.put("tempName" + i, new JSONObject());

JSONObject o = map.get("tempName3"); // get the 4th created (hashmaps don't have an ordering though)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download