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 内容解析为 JSONObject
val jsonObject = JSONObject(existingContent)
// 如果 "tcSettings" 字段不存在,则创建一个空的 JSONArray
val 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()
}
}