【问题标题】:How do I save a JSON file with four spaces indentation using JSON.NET?如何使用 JSON.NET 保存具有四个空格缩进的 JSON 文件?
【发布时间】: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 的 IndentationIndentChar 属性@指定缩进量:

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

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

【问题讨论】:

    标签: c# .net json json.net


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,发现 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);
              }
          }
      }
      

      【讨论】:

      • 我喜欢更完整的代码示例!
      【解决方案3】:

      也许尝试将制表符提供给 IndentChar?

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

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

      【讨论】:

      • 恐怕不是我想要的。该问题专门要求空格缩进。
      【解决方案4】:

      我总结了完整的代码,基于@Guffa's answer

      FileMode.OpenOrCreate 更改为FileMode.Create。否则当新内容变小时文件不会被缩短。

      var config = JObject.Parse(File.ReadAllText("config.json"));
      config["revision"] = 1;
      
      using (FileStream fs = File.Open("config.json", FileMode.Create))
      {
          using (StreamWriter sw = new StreamWriter(fs))
          {
              using (JsonTextWriter jw = new JsonTextWriter(sw))
              {
                  jw.Formatting = Formatting.Indented;
                  jw.IndentChar = ' ';
                  jw.Indentation = 4;
      
                  JsonSerializer serializer = new JsonSerializer();
                  serializer.Serialize(jw, config);
              }
          }
      }
      

      【讨论】:

        【解决方案5】:

        这里有一个扩展方法,可以使 json 易于人类阅读。 它删除属性名称中的引号,将枚举转换为字符串,并使用 4 个空格缩进 json。

        public static string ToPrettyJson(this object obj)
        {
            var json = JsonConvert.SerializeObject(obj, Formatting.Indented, new StringEnumConverter());
            json = Regex.Replace(json, @"^([\s]+)""([^""]+)"": ", "$1$2: ", RegexOptions.Multiline); // no quotes in props
            json = Regex.Replace(json, @"^[ ]+", m => new String(' ', m.Value.Length * 2), RegexOptions.Multiline); // more indent spaces
            return json;
        }
        

        【讨论】:

          猜你喜欢
          • 2021-12-25
          • 1970-01-01
          • 2022-09-28
          • 1970-01-01
          • 2017-08-05
          • 2010-10-29
          • 1970-01-01
          • 2019-03-13
          相关资源
          最近更新 更多