Java写json文件
public class WriterJson {public static void main(String[] args) {// 创建一个 JSON 对象JSONObject jsonObject = new JSONObject();jsonObject.put("case", "testtest");JSONObject jsonObjects = new JSONObject();jsonObjects.put("triggerTime", "testtest");jsonObjects.put("bandwidthKbps", "testtest");jsonObjects.put("lossPercent", "testtest");jsonObjects.put("delayMs", "testtest");jsonObjects.put("jitterBufferMs", "testtest");// 创建一个 JSON 数组JSONArray jsonArray = new JSONArray();jsonObject.put("tcSettings",jsonArray.put(jsonObjects));try (FileWriter file = new FileWriter("data.json")) {file.write(jsonObject.toString());file.flush();} catch (IOException e) {e.printStackTrace();}System.out.println("JSON 文件写入成功!");}}
Kotlin写json文件
private fun tcSettingsData(filePath:String,dtriggerTime:String, dbandwidthKbps:Int, dlossPercent:Int, ddelayMs:Int, djitterBufferMs:Int){// 读取现有 JSON 文件内容val file = File(filePath)val existingContent = file.readText()// 将现有 JSON 内容解析为 JSONObjectval jsonObject = JSONObject(existingContent)// 如果 "tcSettings" 字段不存在,则创建一个空的 JSONArrayval tcSettingsArray = jsonObject.optJSONArray("tcSettings") ?: JSONArray()// 创建要添加的新 JSON 对象val newJsonObject = JSONObject()newJsonObject.put("triggerTime", dtriggerTime)newJsonObject.put("bandwidthKbps", dbandwidthKbps)newJsonObject.put("lossPercent", dlossPercent)newJsonObject.put("delayMs", ddelayMs)newJsonObject.put("jitterBufferMs", djitterBufferMs)// 向 "tcSettings" 数组中添加新 JSON 对象tcSettingsArray.put(newJsonObject)// 将 "tcSettings" 数组放回 JSON 对象jsonObject.put("tcSettings", tcSettingsArray)// 将更新后的 JSON 对象写回到文件try {FileWriter(filePath).use { fileWriter ->fileWriter.write(jsonObject.toString())}} catch (e: IOException) {e.printStackTrace()}}