如何用C#向JSON文件添加对象且不破坏文件格式?
在C#中安全向已有JSON文件添加内容的方法
绝对不要用字符串拼接、手动写入这类方式修改JSON——这种操作极易出现引号未转义、括号不匹配、逗号位置错误等问题,直接破坏文件格式。正确的做法是用官方或成熟的JSON序列化库来解析、修改、重新生成JSON。
以下是两种主流方案:
方案1:使用.NET自带的System.Text.Json(.NET Core/.NET 5+适用)
场景1:JSON根节点是数组
假设你的JSON文件内容如下:
[ {"Name": "Alice", "Age": 30} ]
代码示例:
using System; using System.Collections.Generic; using System.IO; using System.Text.Json; class JsonUpdateExample { static void Main() { string jsonFilePath = "your-file-path.json"; // 1. 读取现有JSON内容 string existingJson = File.ReadAllText(jsonFilePath); // 2. 反序列化为强类型集合 var personList = JsonSerializer.Deserialize<List<Person>>(existingJson); // 3. 添加新内容 personList.Add(new Person { Name = "Bob", Age = 28 }); // 4. 重新序列化并写入文件(保留缩进格式) string updatedJson = JsonSerializer.Serialize(personList, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllText(jsonFilePath, updatedJson); } } // 匹配JSON结构的实体类 public class Person { public string Name { get; set; } public int Age { get; set; } }
场景2:JSON根节点是复杂对象
假设JSON内容是:
{ "Title": "User Collection", "Users": [ {"Name": "Alice", "Age": 30} ] }
代码示例:
using System; using System.Collections.Generic; using System.IO; using System.Text.Json; class JsonUpdateExample { static void Main() { string jsonFilePath = "your-file-path.json"; string existingJson = File.ReadAllText(jsonFilePath); var userCollection = JsonSerializer.Deserialize<UserCollection>(existingJson); userCollection.Users.Add(new Person { Name = "Bob", Age = 28 }); string updatedJson = JsonSerializer.Serialize(userCollection, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllText(jsonFilePath, updatedJson); } } public class UserCollection { public string Title { get; set; } public List<Person> Users { get; set; } } public class Person { public string Name { get; set; } public int Age { get; set; } }
方案2:使用Newtonsoft.Json(Json.NET,兼容.NET Framework/.NET全平台)
如果习惯用Json.NET,代码逻辑类似,写法更简洁:
数组场景示例
using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; class JsonUpdateExample { static void Main() { string jsonFilePath = "your-file-path.json"; string existingJson = File.ReadAllText(jsonFilePath); var personList = JsonConvert.DeserializeObject<List<Person>>(existingJson); personList.Add(new Person { Name = "Bob", Age = 28 }); string updatedJson = JsonConvert.SerializeObject(personList, Formatting.Indented); File.WriteAllText(jsonFilePath, updatedJson); } } public class Person { public string Name { get; set; } public int Age { get; set; } }
动态处理不确定结构的JSON
如果JSON结构不固定,可使用动态类型解析:
System.Text.Json动态处理
using System; using System.IO; using System.Text.Json; class JsonUpdateExample { static void Main() { string jsonFilePath = "your-file-path.json"; using var doc = JsonDocument.Parse(File.ReadAllText(jsonFilePath)); var root = doc.RootElement.Clone(); // 假设根是数组,添加新元素 using var newItem = JsonDocument.Parse(@"{""Name"":""Bob"",""Age"":28}"); var updatedArray = JsonSerializer.SerializeToElement(root.EnumerateArray().Append(newItem.RootElement)); string updatedJson = JsonSerializer.Serialize(updatedArray, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllText(jsonFilePath, updatedJson); } }
Json.NET动态处理
using System; using System.IO; using Newtonsoft.Json.Linq; class JsonUpdateExample { static void Main() { string jsonFilePath = "your-file-path.json"; JArray jsonArray = JArray.Parse(File.ReadAllText(jsonFilePath)); jsonArray.Add(JObject.Parse(@"{""Name"":""Bob"",""Age"":28}")); File.WriteAllText(jsonFilePath, jsonArray.ToString(Formatting.Indented)); } }
内容的提问来源于stack exchange,提问作者Sheldon
相关产品推荐
相关产品推荐

