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

本文详细介绍了如何使用Insus.NET将新增JSON数据合并到已有数据中,并通过代码示例展示了读取、序列化及文件操作的具体实现,旨在解决在数据管理过程中遇到的挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

转载于:https://www.cnblogs.com/insus/p/4344547.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值