Java寫json文件文章來源:http://www.zghlxwxcb.cn/news/detail-626271.html
public class WriterJson {
public static void main(String[] args) {
// 創(chuàng)建一個 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");
// 創(chuàng)建一個 JSON 數(shù)組
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文件文章來源地址http://www.zghlxwxcb.cn/news/detail-626271.html
private fun tcSettingsData(filePath:String,dtriggerTime:String, dbandwidthKbps:Int, dlossPercent:Int, ddelayMs:Int, djitterBufferMs:Int){
// 讀取現(xiàn)有 JSON 文件內(nèi)容
val file = File(filePath)
val existingContent = file.readText()
// 將現(xiàn)有 JSON 內(nèi)容解析為 JSONObject
val jsonObject = JSONObject(existingContent)
// 如果 "tcSettings" 字段不存在,則創(chuàng)建一個空的 JSONArray
val tcSettingsArray = jsonObject.optJSONArray("tcSettings") ?: JSONArray()
// 創(chuàng)建要添加的新 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" 數(shù)組中添加新 JSON 對象
tcSettingsArray.put(newJsonObject)
// 將 "tcSettings" 數(shù)組放回 JSON 對象
jsonObject.put("tcSettings", tcSettingsArray)
// 將更新后的 JSON 對象寫回到文件
try {
FileWriter(filePath).use { fileWriter ->
fileWriter.write(jsonObject.toString())
}
} catch (e: IOException) {
e.printStackTrace()
}
}
到了這里,關(guān)于【Java】java和kotlin關(guān)于Json寫文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!