Mr. White Mr. White - 2 months ago 6
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”: [
{"id":"","label":"year","type":"string"},
{"id":"","label":"sales","type":"number"},
{"id":"","label":"expenses","type":"number"}
],
“rows”: [
{"c":[{"v":"2001"},{"v":3},{"v":5}]},
{“c”:[{"v":"2002"},{"v":5},{"v":10}]},
{“c”:[{"v":"2003"},{"v":6},{"v":4}]},
{“c”:[{"v":"2004"},{"v":8},{"v":32}]},
{“c”:[{"v":"2005"},{"v":3},{"v":56}]}
]
}


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

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)
Comments