早上在學習《Post model至Web Api創建或是保存數據》http://www.cnblogs.com/insus/p/4343833.html ,如果你第二添加時,json文件得到的數據只能是單筆記錄且是最新的。
那需要怎樣把新添加的json數據附加至已經存在的數據中去?本篇Insus.NET就是想實現此功能。
想法是先讀取json文件的數據轉換為數據集存放在內存中,新添加的數據再附加上去,然后再把內存的數據集序列化保存為json文件即可。
上面代碼示例中,有3大部分,第一部分是讀取文件中原有數據:

if (System.IO.File.Exists(existFilePhysicalPath)) { using (System.IO.StreamReader sr = new System.IO.StreamReader(existFilePhysicalPath)) { JsonTextReader jtr = new JsonTextReader(sr); JsonSerializer se = new JsonSerializer(); object obj = se.Deserialize(jtr, typeof(List<Order>)); orders = (List<Order>)obj; } }
其實這部分,簡單一句代碼也可以:

orders = JsonConvert.DeserializeObject<List<Order>>(System.IO.File.ReadAllText(existFilePhysicalPath));
第二部分是將內存中的List<Order>數據序列化之后,存為json文件:

using (FileStream fs = File.Open(newFilePhysicalPath, FileMode.CreateNew)) using (StreamWriter sw = new StreamWriter(fs)) using (JsonWriter jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(jw, orders); }
第三部分是把新創建的文件重命名為舊文件名:

if (System.IO.File.Exists(existFilePhysicalPath)) { File.Delete(existFilePhysicalPath); } if (System.IO.File.Exists(newFilePhysicalPath)) { System.IO.File.Move(newFilePhysicalPath, existFilePhysicalPath); }
在Orders目錄中,新創建一個html網頁SaveJsonToExistFile.html: