添加JSON Data到已經存在的JSON文件中


早上在學習《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;
                }
            }
View Code


其實這部分,簡單一句代碼也可以:

orders = JsonConvert.DeserializeObject<List<Order>>(System.IO.File.ReadAllText(existFilePhysicalPath));
View Code


第二部分是將內存中的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);
            }
View Code


第三部分是把新創建的文件重命名為舊文件名:

if (System.IO.File.Exists(existFilePhysicalPath))
            {
                File.Delete(existFilePhysicalPath);
            }
            if (System.IO.File.Exists(newFilePhysicalPath))
            {
                System.IO.File.Move(newFilePhysicalPath, existFilePhysicalPath);
            }
View Code


在Orders目錄中,新創建一個html網頁SaveJsonToExistFile.html:

 

上面收集合的jQuery代碼,可以參考下面:


Insus.NET所做的練習,一般最后少不了動畫演示:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM