我需要根据数据库查询的结果集创建可变数量的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}]}
]
}
我的问题是,我觉得这应该是一个简单的答案,如何在for循环中创建多个具有唯一名称的JSON对象?我的尝试:
for(int i=0;i<10;i++) {
JSONObject "tempName"+i = new JSONObject();
}
答案 0 :(得分: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
数组不可动态调整大小。如果您需要此类行为,则应使用适当的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)
答案 1 :(得分:1)
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"}
]
答案 2 :(得分: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) {
}
}
}
解决方案已经为Java 7及更少版本的人准备了:)