C# 使用Newtonsoft.Json讀寫Json檔案
阿新 • • 發佈:2020-07-23
json:
{ "Information": [ { "LocationName": "通道1", "Points": [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ] }, { "LocationName": "通道2", "Points": [ [ 11, 2, 3, 4 ], [ 5, 6, 7, 8 ] ] } ] }
讀:
string fileName = @"D:\KSIMSCfg\test.json"; StreamReader file= File.OpenText(fileName); JsonTextReader reader = new JsonTextReader(file); JObject jsonObject = (JObject)JToken.ReadFrom(reader); MessageBox.Show((jsonObject["Information"]).ToList()[1]["Points"][0][0].ToString());//得到11 file.Close();
寫:
string jsonString = File.ReadAllText(fileName, System.Text.Encoding.UTF8);//讀取檔案 JObject jobject = JObject.Parse(jsonString);//解析成json jobject["Information"][0]["LocationName"] = "通道1";//替換需要的檔案 string convertString = Convert.ToString(jobject);//將json裝換為string File.WriteAllText(fileName, convertString,System.Text.Encoding.UTF8);//將內容寫進jon檔案中