我正在使用Json.Net将XML序列化为Json.当我将序列化的字符串写入文件时,它只是一行.我如何通过常用标签和缩进实际看起来像Json?
我需要读取JSON配置文件,修改值,然后再次将修改后的JSON保存回文件.JSON就像它获得的一样简单:
{
"test": "init",
"revision": 0
}
Run Code Online (Sandbox Code Playgroud)
要加载数据并修改值,我这样做:
var config = JObject.Parse(File.ReadAllText("config.json"));
config["revision"] = 1;
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好; 现在,将JSON写回文件.首先我尝试了这个:
File.WriteAllText("config.json", config.ToString(Formatting.Indented));
Run Code Online (Sandbox Code Playgroud)
哪个写文件正确,但缩进只有两个空格.
{
"test": "init",
"revision": 1
}
Run Code Online (Sandbox Code Playgroud)
从文档中看,似乎没有办法以这种方式传递任何其他选项,所以我尝试修改这个例子,这将允许我直接设置Indentation和IndentChar属性JsonTextWriter来指定缩进量:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
但这似乎没有任何影响:文件仍然写有两个空格缩进.我究竟做错了什么?