早上在学习《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));

orders = (List)obj;

}

}

View Code

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

orders = JsonConvert.DeserializeObject>(System.IO.File.ReadAllText(existFilePhysicalPath));

View Code

第二部分是将内存中的List数据序列化之后,存为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所做的练习,一般最后少不了动画演示:

 

查看原文