C# 读写json文件操作
创始人
2025-01-16 05:05:36
0

一、JSON 文件

JSON(全称为JavaScript Object Notation,JavaScript 对象表示法) 是一种轻量级的数据交换格式,用于存储和交换文本信息的语法,类似 XML。它是基于JavaScript语法标准的一个子集,但它独立于 JavaScript,因此许多程序环境能够读取(解读)和生成 JSON。
JavaScript 对象表示法(JSON)是用于将结构化数据表示为 JavaScript 对象的标准格式,通常用于在网站上表示和传输数据(例如从服务器向客户端发送一些数据,因此可以将其显示在网页上)。JSON 可以作为一个对象或者字符串存在,前者用于解读 JSON 中的数据,后者用于通过网络传输 JSON 数据。

二、JSON 语法规则

JSON数据由键值对组成,每个键值对之间用逗号分隔,整个数据以大括号 {} 包裹表示一个对象,或者以中括号 [] 包裹表示一个数组。基本语法结构如下:
1、对象(Object):使用大括号 {} 包裹,键值对之间使用冒号 : 分隔,如 { “name”: “John”, “age”: 30 }。
2、数组(Array):使用中括号 [] 包裹,元素之间使用逗号 , 分隔,如 [ “apple”, “banana”, “orange” ]。
3、使用斜杆 \ 来转义字符。
4、大括号 {} 保存对象,对象可以包含多个数组。
5、中括号 [] 保存数组,数组可以包含多个对象。

三、JSON读取操作类

1、添加 System.Runtime.Serialization 程序集文件

系统程序集文件中有能操作 JSON 文件的 API库文件,在项目 “引用” 上右键,点击“添加引用” ,打开“引用管理器”窗口。
在这里插入图片描述
在程序集中找到 System.Runtime.Serialization ,选中后点击确定。将 System.Runtime.Serialization 文件添加到项目引用中。
在这里插入图片描述

2、JSON读写操作类

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks;  namespace FileOperationsDemo {     public static class JsonHandle     {         ///          /// Json转换成对象         ///          ///          ///          ///          public static T JsonToObject(string jsonText)         {             DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));             MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));             T obj = (T)s.ReadObject(ms);             ms.Dispose();             return obj;         }         ///          /// 对象转换成JSON         ///          ///          ///          ///          public static string ObjectToJSON(T obj)         {             DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));             string result = string.Empty;             using (MemoryStream ms = new MemoryStream())             {                 serializer.WriteObject(ms, obj);                 ms.Position = 0;                  using (StreamReader read = new StreamReader(ms))                 {                     result = read.ReadToEnd();                 }             }             return result;         }         ///          /// 将序列化的json字符串内容写入Json文件,并且保存         ///          /// 路径         /// Json内容         public static void WriteJsonFile(string path, string jsonConents)         {             if (!File.Exists(path))  // 判断是否已有相同文件              {                 using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))                 {                     fs.Seek(0, SeekOrigin.Begin);                     fs.SetLength(0);                     using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))                     {                         sw.WriteLine(jsonConents);                     }                 }             }         }         ///          /// 获取到本地的Json文件并且解析返回对应的json字符串         ///          /// 文件路径         /// Json内容         public static string GetJsonFile(string filepath)         {             string json = string.Empty;             using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))             {                 using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))                 {                     json = sr.ReadToEnd().ToString();                 }             }             return json;         }     } } 

3、使用用例

        ///          /// 读取JSON文件         ///          ///          ///          private void button11_Click(object sender, EventArgs e)         {             openFileDialog1.Title = "Choose JSON File";             openFileDialog1.Filter = "JSON (*.json)|*.json";             openFileDialog1.Multiselect = false;             openFileDialog1.RestoreDirectory = true;             openFileDialog1.InitialDirectory = dir;              if (openFileDialog1.ShowDialog() == DialogResult.OK)             {                 // 获取文件                 string jsonTXT = JsonHandle.GetJsonFile(openFileDialog1.FileName);                 richTextBox5.AppendText(jsonTXT + "\n");             }         }         ///          /// 写入JSON文件         ///          ///          ///          private void button12_Click(object sender, EventArgs e)         {             if (!string.IsNullOrEmpty(richTextBox5.Text.ToString().Trim()))             {                 // JSON反序列化:将JSON 字符串转换成对象                 UDPRecData refData_UDP = JsonHandle.JsonToObject(richTextBox5.Text.ToString().Trim());                 // JSON序列化:将对象转换成JSON 字符串                  string jsonFileDS = JsonHandle.ObjectToJSON(refData_UDP);                  saveFileOpen.Title = "保存文件";                 saveFileOpen.Filter = "JSON (*.json)|*.json";                 saveFileOpen.RestoreDirectory = true;                 saveFileOpen.InitialDirectory = dir;                 saveFileOpen.FilterIndex = 1;                 if (saveFileOpen.ShowDialog() == DialogResult.OK)                 {                     // 保存,输出JSON文件                     JsonHandle.WriteJsonFile(saveFileOpen.FileName, jsonFileDS);                 }             }         } 

此外,还需写一个与JSON数据结构一致的数据类。

using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks;  namespace FileOperationsDemo {     [DataContract]     public class UDPRecData     {         [DataMember(Order = 0)]         public Int32 id { get; set; }         [DataMember(Order = 1)]         public Identification ident { get; set; }         [DataMember(Order = 2)]         public TypeData type { get; set; }         [DataMember(Order = 3)]     }     [DataContract]     public class Identification     {         [DataMember(Order = 0)]         public string airline { get; set; }         [DataMember(Order = 1)]         public string reg { get; set; }         [DataMember(Order = 2)]         public string call { get; set; }         [DataMember(Order = 3)]         public string label { get; set; }     }     [DataContract]     public class TypeData     {         [DataMember(Order = 0)]         public string icao { get; set; }         [DataMember(Order = 1)]         public double wingSpan { get; set; }         [DataMember(Order = 2)]         public double wingArea { get; set; }     } }  

操作的JSON文件

{   "id" : 6711,   "ident" : {     "airline" : "DYH",     "reg" : "D-YVEL",     "call" : "llH1234",     "label" : "Test Temp"   },   "type" : {     "icao" : "Y72",     "wingSpan" : 11.1,     "wingArea" : 16.2   } } 

在这里插入图片描述

四、用字典提取Json

1、需要添加引用(System.Web.Extensions),用JavaScriptSerializer类(using System.Web.Script.Serialization;)反序列化,将字典作为类型提取JSON内数据。

        private void Deserialize()         {             jsonExplorer.Nodes.Clear();             JavaScriptSerializer js = new JavaScriptSerializer();              try             {                 Dictionary dic = js.Deserialize>(txtInput.Text);                  TreeNode rootNode = new TreeNode("Root");                 jsonExplorer.Nodes.Add(rootNode);                 BuildTree(dic, rootNode);             }             catch (ArgumentException argE)             {                 MessageBox.Show("JSON data is not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);             }         } 

2、通过嵌套循环读取Json序列内数组数据,并将所有数据绑定到TreeView控件上。

     public void BuildTree(Dictionary dictionary, TreeNode node)         {             foreach (KeyValuePair item in dictionary)             {                 TreeNode parentNode = new TreeNode(item.Key);                 node.Nodes.Add(parentNode);                  try                 {                     dictionary = (Dictionary)item.Value;                     BuildTree(dictionary, parentNode);                 }                 catch (InvalidCastException dicE) {                     try                     {                         ArrayList list = (ArrayList)item.Value;                         foreach (string value in list)                         {                             TreeNode finalNode = new TreeNode(value);                             finalNode.ForeColor = Color.Blue;                             parentNode.Nodes.Add(finalNode);                         }                                              }                     catch (InvalidCastException ex)                     {                         TreeNode finalNode = new TreeNode(item.Value.ToString());                         finalNode.ForeColor = Color.Blue;                         parentNode.Nodes.Add(finalNode);                     }                 }             }         } 

相关内容

热门资讯

wepoke辅助机器人(透视)... wepoke辅助机器人(透视)wopoker分析器(详细辅助透明挂教程)总是有挂(教你有辅助挂)一、...
第一分钟普及!川南麻将辅助&q... 第一分钟普及!川南麻将辅助"详细辅助详细教程"(总是存在有挂)一、川南麻将辅助AI软件牌型概率发牌机...
wepoke有没有挂(透视)w... wepoke有没有挂(透视)wepower有机器人吗(详细辅助AI教程)确实是有挂(大神真的有挂)w...
第三分钟普及!微乐小程序脚本辅... 第三分钟普及!微乐小程序脚本辅助"详细辅助切实教程"(切实是真的有挂)1、任何微乐小程序脚本辅助ai...
3分钟普及!潮汕暗宝辅助器脚本... 3分钟普及!潮汕暗宝辅助器脚本"详细辅助揭秘教程"(切实是有挂);潮汕暗宝辅助器脚本辅助器中分为三种...
wepok软件透明挂(透视)w... wepok软件透明挂(透视)wepoke机制(详细辅助靠谱教程)切实真的有挂(玩家有挂);1.wep...
九分钟普及!福建大菠萝辅助透视... 九分钟普及!福建大菠萝辅助透视系统"详细辅助切实教程"(竟然真的是有挂)1、许多玩家不知道福建大菠萝...
wepoke辅助插件(透视)w... wepoke辅助插件(透视)wepoke开发者(详细辅助细节揭秘)切实真的有挂(攻略一定有挂)1、每...
第9分钟普及!余干5十k外挂&... 第9分钟普及!余干5十k外挂"详细辅助wepoke教程"(其实有挂)1)余干5十k外挂辅助挂:进一步...
wepoke辅助技巧(透视)w... wepoke辅助技巧(透视)wepoke有挂吗网上靠谱吗(详细辅助总结教程)果然是真的有挂(了解插件...