Change values in JSON file (writing files)

后端 未结 4 2231
爱一瞬间的悲伤
爱一瞬间的悲伤 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:46

    You must have classes to instantiate json values to :

    public class Bot
        {
            public string Username { get; set; }
            public string Password { get; set; }
            public string DisplayName { get; set; }
            public string Backpack { get; set; }
            public string ChatResponse { get; set; }
            public string logFile { get; set; }
            public string BotControlClass { get; set; }
            public int MaximumTradeTime { get; set; }
            public int MaximumActionGap { get; set; }
            public string DisplayNamePrefix { get; set; }
            public int TradePollingInterval { get; set; }
            public string LogLevel { get; set; }
            public string AutoStart { get; set; }
        }
        
     
    
       public class RootObject
        {
            public List Admins { get; set; }
            public string ApiKey { get; set; }
            public string mainLog { get; set; }
            public string UseSeparateProcesses { get; set; }
            public string AutoStartAllBots { get; set; }
            public List Bots { get; set; }
        }
    

    Answer to your Ques(Untested code) :

    //Read file to string
    string json = File.ReadAllText("PATH TO settings.json");
    
    //Deserialize from file to object:
    var rootObject = new RootObject();
    JsonConvert.PopulateObject(json, rootObject);
    
    //Change Value
    rootObject.Bots[0].Password = "password";
    
    // serialize JSON directly to a file again
    using (StreamWriter file = File.CreateText(@"PATH TO settings.json"))
    {
        JsonSerializer serializer = new JsonSerializer();
       serializer.Serialize(file, rootObject);
    }
    

提交回复
热议问题