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

后端 未结 3 1317
无人共我
无人共我 2020-12-15 22:59

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:

{
    "         


        
相关标签:
3条回答
  • 2020-12-15 23:41

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-15 23:44

    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);
    
    0 讨论(0)
  • 2020-12-15 23:46

    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

    0 讨论(0)
提交回复
热议问题