码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-03-17 17:42:50      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

早上在学习《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所做的练习,一般最后少不了动画演示:

 技术分享

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

标签:

原文地址:http://www.cnblogs.com/insus/p/4344547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!