当前位置: 首页 > news >正文

【Java】java和kotlin关于Json写文件

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()}}
http://www.lryc.cn/news/112045.html

相关文章:

  • 【深度学习】采用自动编码器生成新图像
  • 华为云交付
  • dns瞅一瞅
  • springAOP的实例
  • 【JavaEE】深入了解Spring中Bean的可见范围(作用域)以及前世今生(生命周期)
  • P1320 压缩技术(续集版)
  • k8s(七) 叩丁狼 service Ingress
  • Android Studio 关于BottomNavigationView 无法预览视图我的解决办法
  • 【STM32】小电流FOC驱控一体板(开源)
  • 代码分析:循环创建N个子进程——为什么最后一个属于父进程?
  • 【SpringBoot面试题整理-超级有效】
  • 岩土工程仪器多通道振弦传感器信号转换器应用于隧道安全监测
  • 西瓜书读书笔记整理(五)—— 第四章 决策树
  • STM32 4G学习
  • Golang 中实现实时聊天通讯
  • 前端面试的性能优化部分(5)每天10个小知识点
  • 【链表OJ 1】移除链表元素val
  • 复原 IP 地址——力扣93
  • OSPF综合实验
  • 安卓4G核心板开发板_MTK6785/MT6785(Helio G95)安卓手机主板方案
  • Linux 匿名页的生命周期
  • 设计模式概述与UML图
  • 使用Vscode编辑keil工程
  • 编译工具:CMake(一) | 简介与安装
  • 深度学习(34)—— StarGAN(1)
  • ES6系列之let、const、箭头函数使用的坑
  • 4.DNS和负载均衡
  • 【JavaEE进阶】Spring核心与设计思想
  • 实习周记第三周
  • 11. 使用tomcat中碰到的一些问题