C# 使用Newtonsoft.Json读写Json文件
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文件中
添加
JObject jsonObj1 = new JObject(); jsonObj1["StartX"] = x.DragLines[t].X1; jsonObj1["StartY"] = x.DragLines[t].Y1; jsonObj1["EndX"] = x.DragLines[t].X2; jsonObj1["EndY"] = x.DragLines[t].Y2; ((JArray)(jsonObj["ProjectCfg"]["MapConfig"]["DeviceList"].ToList()[locationIndex]["Device"]["Defences"].ToList()[defenceId]["Segments"])).Add(jsonObj1);//.ToList().Add(jsonObj1);