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:
{
"
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);
Maybe try to feed a tab character to the IndentChar?
...
jw.IndentChar = '\t';
...
Accordinging to the documentation, it should use the tab character to indent the JSON instead of the space character. http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_Formatting.htm