如何保存一个JSON文件有四个空格缩进使用JSON.NET? [英] How do I save a JSON file with four spaces indentation using JSON.NET?

查看:933
本文介绍了如何保存一个JSON文件有四个空格缩进使用JSON.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要阅读的JSON配置文件,修改一个值,然后保存修改后的JSON回原来的文件了。该JSON很简单,因为它得到:

I need to read a JSON configuration file, modify a value and then save the modified JSON back to the file again. The JSON is as simple as it gets:

{
    "test": "init",
    "revision": 0
}

要加载数据并修改我这样做值:

To load the data and modify the value I do this:

var config = JObject.Parse(File.ReadAllText("config.json"));
config["revision"] = 1;

到目前为止好;现在,写JSON回文件。首先我想这样的:

So far so good; now, to write the JSON back to the file. First I tried this:

File.WriteAllText("config.json", config.ToString(Formatting.Indented));

这正确地写入该文件,但压痕只有两个空格。

Which writes the file correctly, but the indentation is only two spaces.

{
  "test": "init",
  "revision": 1
}

从文档,它看起来像有没有办法通过这种方式的任何其他选项,所以我试图修改的这个例子这将让我直接设置缩进 IndentChar 的属性 JsonTextWriter 来指定缩进量:

From the documentation, it looks like there's no way to pass any other options in this way, so I tried modifying this example which would allow me to directly set the Indentation and IndentChar properties of the JsonTextWriter to specify the amount of indentation:

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

但是,这似乎并没有产生任何影响:该文件仍然被写入了两个空间缩进。我究竟做错了什么?

But that doesn't seem to have any effect: the file is still written with two space indentation. What am I doing wrong?

推荐答案

现在的问题是,你正在使用 config.ToString(),所以对象已经序列化为一个字符串,格式化,当你把它写使用 JsonTextWriter

The problem is that you are using config.ToString(), so the object is already serialised into a string and formatted when you write it using the JsonTextWriter.

使用一个串行器对象序列化的作家,而不是:

Use a serialiser to serialise the object to the writer instead:

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

这篇关于如何保存一个JSON文件有四个空格缩进使用JSON.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆