如何在JSON文件的数组中添加对象?C#代码问题求助
解决C#将新对象写入JSON数组内部的问题
问题根源
你当前的代码是直接把单个对象的JSON字符串追加到文件末尾,相当于在数组外部额外添加了独立对象,完全破坏了JSON数组的合法结构。正确的做法是操作整个JSON数组对象,而不是拆分文本行处理。
解决方案代码
首先定义与JSON结构匹配的实体类(假设你的estoque是该类的实例):
public class Carro { public string modelo { get; set; } public int ano { get; set; } public string cor { get; set; } public string marca { get; set; } public string placa { get; set; } public string completo { get; set; } public int potencia { get; set; } }
替换原有的文件操作逻辑,改为以下代码:
string filePath = @"C:\Users\willi\Desktop\programas\CarDataBase\data.json"; List<Carro> carros = new List<Carro>(); // 读取现有JSON数组,文件不存在则初始化空列表 if (File.Exists(filePath)) { string existingJson = File.ReadAllText(filePath); carros = JsonSerializer.Deserialize<List<Carro>>(existingJson) ?? new List<Carro>(); } // 将新对象加入集合(即数组内部) carros.Add(estoque); // 序列化回格式化的JSON字符串,保持和手动添加一致的格式 string updatedJson = JsonSerializer.Serialize(carros, new JsonSerializerOptions { WriteIndented = true }); // 覆盖写入文件 File.WriteAllText(filePath, updatedJson);
代码说明
- 读取整个文件内容而非按行读取,避免破坏JSON结构
- 将现有JSON反序列化为集合对象,确保新对象能被正确加入数组
- 使用
WriteIndented = true生成格式化JSON,保持可读性 - 覆盖写入文件,确保最终内容是一个完整的合法JSON数组
内容的提问来源于stack exchange,提问作者user15391900
相关产品推荐
相关产品推荐

