C# 使用Newtonsoft.Json讀寫Json文件


0.json文件

{
  "CAN": false,
  "AccCode": 4294901856,
  "Id": 768,
  "BPointMove": true,
  "L_BPointMoveDelay": "600",
  "R_BPointMoveDelay": "1000"
}

 

1.Read

try
            {
                StreamReader file = File.OpenText("config.json");
                JsonTextReader reader = new JsonTextReader(file);
                JObject jsonObject = (JObject)JToken.ReadFrom(reader);
                CAN_Communication = (bool) jsonObject["CAN"];
                AccCode = (uint) jsonObject["AccCode"];
                Id = (uint) jsonObject["Id"];

                // Configure Json
                BPointMove = (bool)jsonObject["BPointMove"];
                _classLeft.DelayBPointMove = (int)jsonObject["L_BPointMoveDelay"];
                _classRight.DelayBPointMove = (int)jsonObject["R_BPointMoveDelay"];
                file.Close();

            }
            catch
            {
                //MessageBox.Show("CAN卡配置有誤!");
            }

2.Write

try 
                {
                    string json = File.ReadAllText("config.json");
                    dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    jsonObj["L_BPointMoveDelay"] = LBPointdelay.ToString();
                    string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
                    File.WriteAllText("config.json", output);
                }
                catch { }

 


免責聲明!

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



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