Change values in JSON file (writing files)

后端 未结 4 2220
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 15:55

I have a settings.json file present in the Release folder of my application. What I want to do is change the value of it, not temporarily, permanently.. That means, deleting

4条回答
  •  孤城傲影
    2020-11-27 16:34

    Here's a simple & cheap way to do it (assuming .NET 4.0 and up):

    string json = File.ReadAllText("settings.json");
    dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
    jsonObj["Bots"][0]["Password"] = "new password";
    string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
    File.WriteAllText("settings.json", output);
    

    The use of dynamic lets you index right into json objects and arrays very simply. However, you do lose out on compile-time checking. For quick-and-dirty it's really nice but for production code you'd probably want the fully fleshed-out classes as per @gitesh.tyagi's solution.

提交回复
热议问题