如何使用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
,似乎没有办法以这种方式传递任何其他选项,所以我尝试修改这个例子 ,这将允许我直接设置IndentChar
的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()); } } }
但这似乎没有任何影响:文件仍然写有两个空格缩进。 我究竟做错了什么?
问题是您使用的是config.ToString()
,因此当您使用JsonTextWriter
编写对象时,该对象已经被序列化为字符串并进行格式化。
使用序列化器将对象序列化到编写器:
JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(jw, config);
也许尝试将制表符添加到IndentChar?
... jw.IndentChar = 't'; ...
根据文档,它应该使用制表符来缩进JSON而不是空格字符。 https://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_Formatting.htm
上述就是C#学习教程:如何使用JSON.NET保存带有四个空格缩进的JSON文件?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1006456.html