C#中如何向JSON文本文件插入新数据?
向JSON文本文件添加新员工数据的实现方法
核心实现步骤
要向存储员工列表的JSON文件添加新数据,需遵循以下流程:
- 读取现有JSON文件内容
- 将JSON反序列化为
List<EmployeeItem>集合 - 创建新的
EmployeeItem对象并添加到集合中 - 将更新后的集合重新序列化为JSON字符串
- 将新的JSON字符串写回原文件
现有代码问题说明
Writeemployee方法逻辑错误:遍历现有员工集合时,重复创建空的EmployeeItem对象,未将新数据添加到原集合,也没有写回文件的逻辑AddEmployeee方法为空实现,且使用async void(异步方法建议用async Task避免异常无法捕获)
完整正确实现代码
同步版本(适合非UI场景)
public static void AddNewEmployeeToFile(EmployeeItem newEmployee) { var path = @"text file\GetAllEmp.txt"; // 读取现有JSON内容 string rawJson = File.ReadAllText(path, Encoding.UTF8); // 反序列化为员工列表,处理文件为空的情况 List<EmployeeItem> empList = string.IsNullOrEmpty(rawJson) ? new List<EmployeeItem>() : JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson); // 添加新员工到列表 empList.Add(newEmployee); // 重新序列化为格式化的JSON(方便阅读) string updatedJson = JsonConvert.SerializeObject(empList, Formatting.Indented); // 写回文件 File.WriteAllText(path, updatedJson, Encoding.UTF8); }
异步版本(推荐UI场景,避免阻塞界面)
public static async Task AddNewEmployeeToFileAsync(EmployeeItem newEmployee) { var path = @"text file\GetAllEmp.txt"; // 异步读取文件 string rawJson = await File.ReadAllTextAsync(path, Encoding.UTF8); List<EmployeeItem> empList = string.IsNullOrEmpty(rawJson) ? new List<EmployeeItem>() : JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson); empList.Add(newEmployee); string updatedJson = JsonConvert.SerializeObject(empList, Formatting.Indented); // 异步写回文件 await File.WriteAllTextAsync(path, updatedJson, Encoding.UTF8); }
修正后的数据访问方法
// 改用async Task,避免async void的潜在问题 public static async Task AddEmployeeAsync(EmployeeItem employee) { await AddNewEmployeeToFileAsync(employee); }
调用示例
// 创建新员工对象并填充属性 var newEmp = new EmployeeItem { SiteID = 1001, Name = "张三", Department = "技术部" // 填充其他所需属性 }; // 同步调用 AddNewEmployeeToFile(newEmp); // 异步调用(需在异步方法内执行) // await AddEmployeeAsync(newEmp);
关键注意事项
- 空文件处理:如果文件是新建的无内容,直接反序列化会报错,需先判断JSON字符串是否为空,为空则创建空列表
- 编码一致性:读取和写入都使用
Encoding.UTF8,避免出现乱码 - JSON格式化:使用
Formatting.Indented生成易读的JSON格式,若追求文件体积可改用Formatting.None生成紧凑格式
内容的提问来源于stack exchange,提问作者ailsa
相关产品推荐
相关产品推荐

