我正在使用 org.json.simple.JSONObject 库读取一些文本并将其形成 JSON。
我的代码如下:
public class PerfMetrics {
private static String filePath = "Shell_Pricing_Metrics.json";
private static String jsoncontent;
public static void clearFileContents(String filePath) throws IOException {
File f1 = new File(filePath);
new FileWriter(f1);
}
public static void metricAsJSON(String testName, long testTime) {
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
JSONObject obj = new JSONObject();
obj.put("testname", testName);
obj.put("Duration", testTime);
obj.put("Timestamp", ts.toString());
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(obj.toJSONString());
jsoncontent = gson.toJson(je);
JsonArray jsonArray = new JsonArray();
jsonArray.add(je);
jsoncontent = gson.toJson(jsonArray);
}
public static void writeJsonToFile() {
try {
File f1 = new File(filePath);
if (!(f1.exists())) {
f1.createNewFile();
}
FileWriter fw1 = new FileWriter(f1, true);
PrintWriter pw1 = new PrintWriter(fw1);
if (f1.exists() && f1.isFile()) {
pw1.println(jsoncontent);
pw1.flush();
pw1.close();
fw1.close();
} else {
System.out.println("Please provide a valid path to destination Json file");
}
} catch(Exception e){
e.printStackTrace();
}
}
}
写入文件为:
[
{
"Duration": 30,
"testname": "Upload Data click to Model Prices dropdown display time:",
"Timestamp": "2019-10-15 09:47:53.804"
}
]
我需要的数据为:
[
{
"testname": "Shopping dropdown display time:",
"Duration": 2156,
"Timestamp": "2019-10-10 14:29:01.945"
},
{
"testname": "Clothing dropdown display time:",
"Duration": 3567,
"Timestamp": "2019-10-10 14:30:01.534"
},
{
"testname": "Electrical dropdown display time:",
"Duration": 2098,
"Timestamp": "2019-10-10 14:33:01.532"
},
{
"testname": "Toys dropdown display time:",
"Duration": 4562,
"Timestamp": "2019-10-10 14:35:01.435"
}
]
我可以用我有限的 Java 技能笨拙地解决这个问题,但想知道支持对象字符串转换为 Json 数组的最佳库/实践是什么?
最佳答案
看起来您每个 JSONObject
使用一次该函数,并且每次都写入文件 - 如果是这种情况,那么您可以从中返回 JSONObject
方法:
/*... obj.put(key, value); obj.put('Timestamp') ... */
return obj;
然后,在您现在调用 .metricAsJSON
的地方,将其附加到 JSONArray
对象,如下所示:
JSONArray arr = new JSONArray();
for (... metric in some other array ...) {
JSONObject obj = GetMetrics.metricAsJSON(key, value);
arr.put(obj);
}
String jsonString = arr.toString();
/* Write jsonString to file */
如果您需要动态添加值并多次写入,可以将 JSONArray
存储为方法变量,或者每次将文件加载到 JSONArray
对象中需要在末尾添加一些内容。
关于java - 将 JSON 对象列表转换为单个 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58374466/