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

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

从文档IndentChar ,似乎没有办法以这种方式传递任何其他选项,所以我尝试修改这个例子 ,这将允许我直接设置IndentCharIndentationIndentChar属性来指定缩进量:

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

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

问题是您使用的是config.ToString() ,因此当您使用JsonTextWriter编写对象时,该对象已经被序列化为字符串并进行格式化。

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

 JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(jw, config); 

也许尝试将制表符添加到IndentChar?

 ... jw.IndentChar = '\t'; ... 

根据文档,它应该使用制表符来缩进JSON而不是空格字符。 http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_Formatting.htm