如何使用JSON.NET保存带有四个空格缩进的JSON文件?

Mar*_*ell 13 .net c# json json.net

我需要读取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)

从文档中看,似乎没有办法以这种方式传递任何其他选项,所以我尝试修改这个例子,这将允许我直接设置IndentationIndentChar属性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)

但这似乎没有任何影响:文件仍然写有两个空格缩进.我究竟做错了什么?

Guf*_*ffa 13

问题是您正在使用config.ToString(),因此该对象已经被序列化为一个字符串,并在您使用时将其编写为格式JsonTextWriter.

使用序列化器将对象序列化到编写器:

JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, config);
Run Code Online (Sandbox Code Playgroud)


小智 7

我遇到了同样的问题,发现 WriteRaw 不会影响缩进设置,但是您可以在 JObject 上使用 WriteTo 来解决问题

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;

            config.WriteTo(jw);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)