0

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();
}
Dennis
  • 3,962
  • 7
  • 26
  • 44

3 Answers3

5

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)
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
5
JSONArray arr = new JSONArray();
              HashMap<String, JSONObject> map = new HashMap<String, JSONObject>();
              for(int i = 0 ; i < 10 ; i++) {
                JSONObject json=new JSONObject();
                json.put("id",i);
                json.put("firstName","abc"+i);
                map.put("json" + i, json);
                arr.put(map.get("json" + i));
              }
    System.println("The json string is " + arr.toString());

OutPut is 

The json string is 
[
  {"id":0,"firstName":"abc0"},
  {"id":1,"firstName":"abc1"},
  {"id":2,"firstName":"abc2"},
  {"id":3,"firstName":"abc3"},
  {"id":4,"firstName":"abc4"}
]
user1105412
  • 77
  • 2
  • 9
0
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;

/**
 * Some solution for write files from different folders to JSON
 * @author Dmytro Melnychuk
 */
public class ParseFilesToJson {
    public static void main(String[] args) {
        List<String> folderNames = Arrays.asList("dwg", "eta-en", "eta-pl", "inst", "prod", "tds-en", "tds-pl");
        folderNames.forEach(it -> {
            writeIntoFile(it);
        });
    }
    private static void writeIntoFile(String folderName) {
        File directory = new File("C:\\Users\\mel\\AppData\\Roaming\\data\\" + folderName);
        File[] directories = directory.listFiles();
        JSONArray array = new JSONArray();
        JSONObject json;
        for (int i = 0; i < directories.length; i++) {
            json = new JSONObject();
            json.put("name", directories[i].getName());
            json.put("version", 1);
            array.put(json);
        }
        try (Writer file = new FileWriter("d:\\" + folderName + ".json")) {
            array.write(file, 2, 0);
        } catch (IOException e) {
        }
    }
}

Solution has prepared for people with Java 7 and less :)

Dmytro Melnychuk
  • 2,285
  • 21
  • 23