星空网 > 软件开发 > ASP.net

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

早上在学习《Post model至Web Api创建或是保存数据》http://www.cnblogs.com/insus/p/4343833.html ,如果你第二添加时,json文件得到的数据只能是单笔记录且是最新的。

那需要怎样把新添加的json数据附加至已经存在的数据中去?本篇Insus.NET就是想实现此功能。

想法是先读取json文件的数据转换为数据集存放在内存中,新添加的数据再附加上去,然后再把内存的数据集序列化保存为json文件即可。
添加JSON Data到已经存在的JSON文件中

上面代码示例中,有3大部分,第一部分是读取文件中原有数据:

添加JSON Data到已经存在的JSON文件中添加JSON Data到已经存在的JSON文件中
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


其实这部分,简单一句代码也可以:

添加JSON Data到已经存在的JSON文件中添加JSON Data到已经存在的JSON文件中
orders = JsonConvert.DeserializeObject<List<Order>>(System.IO.File.ReadAllText(existFilePhysicalPath));

View Code


第二部分是将内存中的List<Order>数据序列化之后,存为json文件:

添加JSON Data到已经存在的JSON文件中添加JSON Data到已经存在的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


第三部分是把新创建的文件重命名为旧文件名:

添加JSON Data到已经存在的JSON文件中添加JSON Data到已经存在的JSON文件中
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:
添加JSON Data到已经存在的JSON文件中

 

上面收集合的jQuery代码,可以参考下面:
添加JSON Data到已经存在的JSON文件中

Insus.NET所做的练习,一般最后少不了动画演示:

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




原标题:添加JSON Data到已经存在的JSON文件中

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流