Java 如何通过 for 循环创建多个 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18688298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create multiple JSON objects via for loop
提问by Dennis
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.
我需要根据数据库查询的结果集创建可变数量的 JSON 对象和 JSON 数组。JSON 格式与以下用于 google 图表的格式非常相似。
{
“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 循环中创建多个具有唯一名称的 JSON 对象?我的尝试:
for(int i=0;i<10;i++) {
JSONObject "tempName"+i = new JSONObject();
}
采纳答案by Sotirios Delimanolis
Java variable names cannot be constructed dynamically.
Java 变量名不能动态构造。
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
.
数组不能动态调整大小。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)
回答by user1105412
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"}
]
回答by Dmytro Melnychuk
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 :)
解决方案已经为 Java 7 及以下版本的人准备好了:)