一、json格式簡介
就是鍵值對形式,{}是對象,[]是數組,相互組合構建。
示例文件Untitled-1.json
{ "unitinfo": [ { "name": "unit1", "bearing": { "1": "1,2", "2": "3,4", "3": "5,6", "4": "7,8", "5": "9,10", "6": "11,12", "7": "13,14", "8": "15,16" }, "modules": "path1" }, { "name": "unit2", "bearing": { "1": "aaa", "2": "bbb", "3": "ccc", "4": "ddd", "5": "eee", "6": "fff", "7": "fff", "8": "fff" }, "modules": "path3" } ], "equipmentinfo":[{ "name":"a1", "model":"patha1" }] }
二、引入Newtonsoft.Json
右擊引用,在NuGet程序包中搜索下載
三、讀取操作的代碼
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; namespace ConsoleApp2 { class Program { static void Main(string[] args) { string filepath = @"C:\Users\Administrator\source\repos\ConsoleApp2\Untitled-1.json"; using (StreamReader file=new StreamReader(filepath)) { using (JsonTextReader reader=new JsonTextReader(file)) { JObject jobj = (JObject)JToken.ReadFrom(reader); Console.WriteLine("最上層對象總數:"+jobj.Count); var j1 = jobj["unitinfo"];//按鍵值對的用法取鍵為"unitinfo"的值 Console.WriteLine("unitinfo數組長度:"+j1.Count());//JToken對象沒有Count屬性,但有Count()方法 //"unitinfo"的值是一個數組,遍歷數組 foreach (var item in j1) { Console.WriteLine("組別:"+item["name"]); var ib = item["bearing"];//取鍵為"bearing"的值 Console.WriteLine("bearing值對象內屬性的總數:"+ib.Count());//取 //"bearing"的值是對象,也可以遍歷,將子對象轉成JProperty類型,就可以獲取鍵值name/value foreach (JProperty item2 in item["bearing"]) { Console.WriteLine("鍵為"+item2.Name+"值為" + item2.Value); } } } } Console.ReadKey(); } } }
運行結果:
四、修改操作
待續...