Use the JObject
class in Newtonsoft.Json.Linq
to modify JSON values without knowing the JSON structure ahead of time:
using Newtonsoft.Json.Linq;
string jsonString = File.ReadAllText("myfile.json");
// Convert the JSON string to a JObject:
JObject jObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString) as JObject;
// Select a nested property using a single string:
JToken jToken = jObject.SelectToken("Bots[0].Password");
// Update the value of the property:
jToken.Replace("myNewPassword123");
// Convert the JObject back to a string:
string updatedJsonString = jObject.ToString();
File.WriteAllText("myfile.json", updatedJsonString);
Example:
// This is the JSON string from the question
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("myNewPassword123");
// 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
// }
// ]
//}