首页 > 解决方案 > 如何将 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"
  }
]

标签: jsongson

解决方案


推荐阅读