2014-09-11 18 views
13

我需要讀取JSON配置文件,修改一個值,然後再次將修改後的JSON保存迴文件。該JSON很簡單,因爲它得到:如何使用JSON.NET使用四個空格縮進來保存JSON文件?

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

加載數據和修改我這樣做的價值:

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

到目前爲止好;現在,將JSON寫回文件。首先我試過這個:

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

它正確寫入文件,但縮進只有兩個空格。

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

從文檔,它看起來像有沒有辦法通過這樣的任何其他選項,所以我試圖修改this example這將讓我直接設置JsonTextWriterIndentationIndentChar屬性指定金額縮進:

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

但是,這似乎沒有任何影響:該文件仍寫入兩個空間縮進。我究竟做錯了什麼?

回答

12

的問題是,你正在使用config.ToString(),所以對象已被序列化到一個字符串和格式化,當你寫它使用JsonTextWriter

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

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

是的,就是這樣:現在你已經指出它是完全合理的。謝謝! – 2014-09-11 13:43:30

相關問題