在JSON文件变化值(写入文件) [英] Change values in JSON file (writing files)

查看:209
本文介绍了在JSON文件变化值(写入文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在我的应用程序的发布文件夹中的文件settings.json。我想要做的是改变了它的价值,而不是暂时,永久性..这意味着,删除旧的条目,编写一个新的,并保存它。

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 the old entry, writing a new one and saving it.

下面是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"
    }
]
}

假设我想修改密码值,而不是BOT密码我想这是唯一的密码。 ?我该怎么做了。

Suppose I want to change the password value and instead of BOT PASSWORD I want it to be only password. How do I do that?

推荐答案

下面是一个简单的&安培;廉价的方式做到这一点(假设.NET 4.0及以上):

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



使用动态的让您指数权成JSON对象和数组很干脆。但是,你失去了编译时检查。为了快速和肮脏的它真的很好,但生产代码,你可能希望完全充实淘汰类按@ gitesh.tyagi的解决方案。

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.

这篇关于在JSON文件变化值(写入文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆