更改JSON文件中的值(写入文件)

Bon*_*one 21 c# json

我的应用程序的Release文件夹中有一个settings.json文件.我想要做的是更改它的值,而不是暂时,永久..这意味着,删除旧条目,写一个新条目并保存它.

这是JSON文件的格式

{
"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"
    }
]
}
Run Code Online (Sandbox Code Playgroud)

假设我想更改密码值而不是BOT PASSWORD我希望它只是密码.我怎么做?

age*_*ega 42

这是一个简单而廉价的方法(假设.NET 4.0及以上版本):

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);
Run Code Online (Sandbox Code Playgroud)

使用它dynamic可以非常简单地将索引直接索引到json对象和数组中.但是,您确实会失去编译时检查.对于快速和肮脏的它真的很好,但对于生产代码,你可能想要完全充实的类,根据@ gitesh.tyagi的解决方案.

  • @Alexander:因为DeserializeObject的返回类型是普通的`object`.如果json的内容是一个简单的字典(没有嵌套数组或子对象),你可以使用`var jsonObj = JsonConvert.DeserializeObject <Dictionary <string,string >>(json);`并获取一个字典.或者,如果您只需要选择某些值,请参阅[此答案](/sf/answers/332482881/)以获取其他方法. (2认同)

Jos*_*hee 20

使用JObjectin 类Newtonsoft.Json.Linq修改 JSON 值,无需提前了解 JSON 结构:

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);
Run Code Online (Sandbox Code Playgroud)

例子:

// 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
//    }
//  ]
//}
Run Code Online (Sandbox Code Playgroud)


git*_*agi 10

您必须具有类以将json值实例化为:

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; }
    }
Run Code Online (Sandbox Code Playgroud)

回答你的问题(未经测试的代码):

//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);
}
Run Code Online (Sandbox Code Playgroud)