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);

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM