How do I save a JSON file with four spaces indentation using JSON.NET?
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);