json - 如何将 JsonObject 连接/附加到 JsonArray
问题描述
鉴于以下代码在代码中被不同地调用,然后被写入文件(单独的方法),我只需要将下一个值附加到数组中。这可能是一个简单的 Collections 问题,但不确定是否有专门的 Gson 方式来执行此操作:
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 JsonArray appendMetricAsJson(String jsoncontent){
JsonArray jsonContentList = new JsonArray();
jsonContentList.add(jsoncontent);
return jsonContentList;
FileWriter fw1 = new FileWriter(f1, true);
PrintWriter pw1 = new PrintWriter(fw1);
if (f1.exists() && f1.isFile()) {
pw1.println(jsonContentList);
pw1.flush();
pw1.close();
fw1.close();
}
}
电流输出:
[
{
"Duration": 30,
"testname": "Shopping link click to dropdown display time:",
"Timestamp": "2019-10-15 09:47:53.804"
}
]
期望的输出:
[
{
"Duration": 30,
"testname": "Shopping link click to dropdown display time:",
"Timestamp": "2019-10-15 09:45:13.334"
},
{
"Duration": 16,
"testname": "Clothing link click to dropdown display time",
"Timestamp": "2019-10-15 09:44:34.356"
},
{
"Duration": 24,
"testname": "Toys link click to dropdown display time",
"Timestamp": "2019-10-15 09:46:33.453"
},
{
"Duration": 34,
"testname": "Electrics link click to dropdown display time",
"Timestamp": "2019-10-15 09:47:53.566"
}
]
解决方案
推荐阅读
- vue.js - 如何在 Vue Lifecycle 中检测组件的哪些数据已更新?
- r - 如何将数据框转换为所需的结构和形式?
- python - 在 PyCharm docker Interpreter 选项卡中丢失
- java - 数据绑定 - 找不到 BR 类
- windows - 通过powershell在windows 2019上安装远程桌面开放许可证
- typescript - 在 deno 记录器的控制台中看不到
- python - 非线性梯度下降不能很好地收敛
- javascript - 尝试从 subscribe() 获取 json 数据 - Angular 7.x
- excel - 排序适用于 2016 Excel 版本,但不适用于 2010
- html - 在 Power 门户中添加 Dynamics CRM HTML Webresource