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

C#-Json文件的读写

文章速览

  • 命名空间
  • 读取Json
    • 核心代码
    • 示例
  • 写入Json
    • 核心代码
    • 示例

坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~

命名空间

using Newtonsoft.Json;

读取Json

核心代码

                //核心代码using (StreamReader file = File.OpenText(filePath)){JsonSerializer serializer = new JsonSerializer();var ret = (类型)serializer.Deserialize(file, typeof(类型));}

示例

        Dictionary<string, double> LoadDictionaryFromFile(){Dictionary<string, double> ret = new Dictionary<string, double>();try{if (!Directory.Exists(folderPath)){//检查文件目录是否存在Directory.CreateDirectory(folderPath);}var filePath = Path.Combine(folderPath, FileName);if (!File.Exists(filePath)){File.Create(filePath);}else{//核心代码using (StreamReader file = File.OpenText(filePath)){JsonSerializer serializer = new JsonSerializer();ret = (Dictionary<string, double>)serializer.Deserialize(file, typeof(Dictionary<string, double>));}}}catch (Exception ex){MainDeviceProvider.Instance.Logger.Error("解析出现错误!",ex);}return ret;}

写入Json

核心代码

var filePath = Path.Combine(folderPath, FileName);string data = JsonConvert.SerializeObject(dataDictionary, Formatting.Indented);File.WriteAllText(filePath, data);

示例

void SaveDataToFile(){try{var filePath = Path.Combine(folderPath, FileName);string data = JsonConvert.SerializeObject(dataDictionary, Formatting.Indented);File.WriteAllText(filePath, data);}catch(Exception ex){MainDeviceProvider.Instance.Logger.Error("写入出现错误!", ex);}}
http://www.lryc.cn/news/378571.html

相关文章:

  • 【2023级研究生《人工智能》课程考试说明】
  • C语言队列操作及其安全问题
  • next.js v14 升级全步骤|迁移 pages Router 到 App Router
  • 如何在Ubuntu上安装WordPress
  • 处理导入Excel文件过大导致Zip bomb detected的问题
  • 【FFmpeg】AVIOContext结构体
  • Python控制结构
  • OpenCV--图形轮廓
  • MYSQL通过EXPLAIN关键字来分析SQL查询的执行计划,判断是否命中了索引
  • clean code-代码整洁之道 阅读笔记(第十二章)
  • FFmpeg YUV编码为H264
  • 【C语言】顺序表(上卷)
  • Luma AI如何注册:文生视频领域的新星
  • 一站式实时数仓Hologres整体能力介绍
  • 如何在 Windows 上安装 Docker Desktop
  • WPF由文本框输入的内容动态渲染下拉框
  • RPCMon:一款基于ETW的RPC监控工具
  • 【odoo】常用的字符转义:“>“,“<“,““,“/“等
  • 李宏毅深度学习项目——HW1个人笔记
  • 3D Gaussian Splatting Windows安装
  • 人脸识别——可解释的人脸识别(XFR)人脸识别模型是根据什么来识别个人的
  • 仓库管理系统的设计
  • 最火AI角色扮演流量已达谷歌搜索20%!每秒处理2万推理请求,Transformer作者公开优化秘诀
  • MySQL:MySQL分组排序函数rank()、row_number()、dense_rank()与partition by结合使用
  • opencv c++ 检测图像尺寸大小,标注轮廓
  • Python数据可视化基础:使用Matplotlib绘制图表
  • Java开发接口设计的原则
  • [火灾警报系统]yolov5_7.0-pyside6火焰烟雾识别源码
  • 机器学习和深度学习区别
  • 【功能详解】银河麒麟操作系统“安全启动”是如何发挥作用的?