Changing values โ€‹โ€‹in a JSON file (writing files)

I have a settings.json file present in the Release folder of my application. What I want to do is change its meaning, and not temporarily, forever. This means deleting an old record, recording a new one and saving it.

Here is the JSON file format

{ "Admins":["234567"], "ApiKey":"Text", "mainLog": "syslog.log", "UseSeparateProcesses": "false", "AutoStartAllBots": "true", "Bots": [ { "Username":"BOT USERNAME", "Password":"BOT PASSWORD", "DisplayName":"TestBot", "Backpack":"", "ChatResponse":"Hi there bro", "logFile": "TestBot.log", "BotControlClass": "Text", "MaximumTradeTime":180, "MaximumActionGap":30, "DisplayNamePrefix":"[AutomatedBot] ", "TradePollingInterval":800, "LogLevel":"Success", "AutoStart": "true" } ] } 

Suppose I want to change the password, and instead of BOT PASSWORD I want it to be just a password. How to do it?

+15
source share
3 answers

Here is a simple and cheap way to do this (assuming .NET 4.0 and above):

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

Using dynamic makes it very easy to index directly into json objects and arrays. However, you lose when checking the compilation time. For quick and dirty this is really nice, but for production code, you probably want to completely form the classes according to @ gitesh.tyagi's solution.

+31
source

You must have classes to create json values โ€‹โ€‹for:

 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<string> 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<Bot> Bots { get; set; } } 

Answer to your question (unverified code):

 //Read file to string string json = File.ReadAllText("PATH TO settings.json"); //Deserialize from file to object: 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); } 
+9
source

Use the JObject class in Newtonsoft.Json.Linq to do this without knowing the JSON structure beforehand:

 using Newtonsoft.Json.Linq; string jsonString = File.ReadAllText("myfile.json"); JObject jObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString) as JObject; // Select a nested property using a single string: JToken jToken = jObject.SelectToken("Bots[0].Password"); jToken.Replace("password"); string updatedJsonString = jObject.ToString(); File.WriteAllText("myfile.json", updatedJsonString); 

Example:

 string jsonString = "{\"Admins\":[\"234567\"],\"ApiKey\":\"Text\",\"mainLog\":\"syslog.log\",\"UseSeparateProcesses\":\"false\",\"AutoStartAllBots\":\"true\",\"Bots\":[{\"Username\":\"BOT USERNAME\",\"Password\":\"BOT PASSWORD\",\"DisplayName\":\"TestBot\",\"Backpack\":\"\",\"ChatResponse\":\"Hi there bro\",\"logFile\":\"TestBot.log\",\"BotControlClass\":\"Text\",\"MaximumTradeTime\":180,\"MaximumActionGap\":30,\"DisplayNamePrefix\":\"[AutomatedBot] \",\"TradePollingInterval\":800,\"LogLevel\":\"Success\",\"AutoStart\":\"true\"}]}"; JObject jObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString) as JObject; // Update a string value; JToken jToken = jObject.SelectToken("Bots[0].Password"); jToken.Replace("password"); // Update an integer value: JToken jToken2 = jObject.SelectToken("Bots[0].TradePollingInterval"); jToken2.Replace(555); // Update a boolean value: JToken jToken3 = jObject.SelectToken("Bots[0].AutoStart"); jToken3.Replace(false); // Get an indented/formatted string: string updatedJsonString = jObject.ToString(); //Output: //{ // "Admins": [ // "234567" // ], // "ApiKey": "Text", // "mainLog": "syslog.log", // "UseSeparateProcesses": "false", // "AutoStartAllBots": "true", // "Bots": [ // { // "Username": "BOT USERNAME", // "Password": "password", // "DisplayName": "TestBot", // "Backpack": "", // "ChatResponse": "Hi there bro", // "logFile": "TestBot.log", // "BotControlClass": "Text", // "MaximumTradeTime": 180, // "MaximumActionGap": 30, // "DisplayNamePrefix": "[AutomatedBot] ", // "TradePollingInterval": 555, // "LogLevel": "Success", // "AutoStart": false // } // ] //} 
0
source

All Articles