【发布时间】:2014-09-11 13:25:43
【问题描述】:
我需要读取一个 JSON 配置文件,修改一个值,然后将修改后的 JSON 再次保存回该文件。 JSON 非常简单:
{
"test": "init",
"revision": 0
}
要加载数据并修改值,我这样做:
var config = JObject.Parse(File.ReadAllText("config.json"));
config["revision"] = 1;
到目前为止一切顺利;现在,将 JSON 写回文件。首先我尝试了这个:
File.WriteAllText("config.json", config.ToString(Formatting.Indented));
哪个写文件正确,但是缩进只有两个空格。
{
"test": "init",
"revision": 1
}
从文档来看,使用此方法似乎无法传递任何其他选项,因此我尝试修改 this example,这将允许我直接设置 @987654328 的 Indentation 和 IndentChar 属性@指定缩进量:
using (FileStream fs = File.Open("config.json", FileMode.OpenOrCreate))
{
using (StreamWriter sw = new StreamWriter(fs))
{
using (JsonTextWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
jw.IndentChar = ' ';
jw.Indentation = 4;
jw.WriteRaw(config.ToString());
}
}
}
但这似乎没有任何效果:文件仍然写有两个空格缩进。我做错了什么?
【问题讨论】: