如何通过for循环创建多个JSON对象

Den*_*nis 0 java json google-visualization

我需要根据数据库查询的结果集创建可变数量的JSON对象和JSON数组.JSON格式看起来非常类似于用于谷歌图表的以下内容.

{
“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}]}
]
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,我觉得这应该是一个简单的答案,如何在for循环中创建具有唯一名称的多个JSON对象?我的尝试:

for(int i=0;i<10;i++) {
    JSONObject "tempName"+i = new JSONObject();
}
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 5

无法动态构造Java变量名.

我不知道现在还没有人回答这个问题但是你在这里.

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
Run Code Online (Sandbox Code Playgroud)

数组不能动态调整大小.List如果您需要此类行为,则应使用适当的实现.如果要按名称访问元素,也可以使用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)
Run Code Online (Sandbox Code Playgroud)


小智 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"}
]
Run Code Online (Sandbox Code Playgroud)