c# How do I save a JSON file with four spaces indentation using JSON.NET?




(3)

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;

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
}

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?


I ran into the same issue and found out that WriteRaw does not effect the indentation settings, however you can solve the issue using WriteTo on the JObject

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

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.net