C#序列化TransactionLogs类到JSON文件报空引用异常如何解决
空引用异常修复
根因
你实例化TransactionLogs类后,其transLogs列表属性未做初始化,默认值为null,直接遍历该属性就会触发空引用异常。同时原有逻辑存在偏差:当前场景是新增一条交易日志,无需遍历现有列表,应该直接构造新的日志对象添加到列表中。
修复步骤
- 给
TransactionLogs类添加构造函数,自动初始化列表,避免后续重复出现空引用问题:
public partial class TransactionLogs { [JsonProperty("TransactionLog")] public List<TransactionLog> transLogs { get; set; } // 新增构造函数 public TransactionLogs() { transLogs = new List<TransactionLog>(); } }
正确实现JSON追加写入
原逻辑问题
直接用StreamWriter追加序列化后的新对象,会导致JSON文件格式损坏:原有文件是完整的JSON对象,直接追加新的JSON字符串会生成多个独立的JSON结构,不符合JSON语法规范,后续反序列化会失败。
正确实现逻辑
先读取已有文件内容反序列化为对象,把新日志追加到列表后,再全量序列化覆盖写入原文件,完整代码如下:
private void toolPull_Click(object sender, EventArgs e) { string jsonPath = @"C:\transactionlog.json"; double cost = Convert.ToDouble(active_Cost.Text); int serial = Convert.ToInt32(transactionSerial_Box.Text); DateTime timeNow = DateTime.Now; // 构造新的日志条目 TransactionLog newLog = new TransactionLog() { Employee = transactionEmployee_Box.Text, Serial = serial, Cost = cost, Description = active_Description.Text, CurrentDate = timeNow, IsPull = true }; TransactionLogs logs; // 读取现有文件内容 if (File.Exists(jsonPath)) { string existJson = File.ReadAllText(jsonPath); logs = JsonConvert.DeserializeObject<TransactionLogs>(existJson); // 兼容文件为空/反序列化失败的场景 logs ??= new TransactionLogs(); } else { logs = new TransactionLogs(); } // 追加新日志 logs.transLogs.Add(newLog); // 全量写入保证JSON格式正确,加缩进格式化方便阅读 string stringJson = JsonConvert.SerializeObject(logs, Formatting.Indented); File.WriteAllText(jsonPath, stringJson); }
注意事项
- 你现有JSON文件中第一条数据存在笔误
_ost,请修正为cost,否则反序列化时这条数据的cost字段会被赋值为默认值0 - 直接使用
File类静态方法读写文件,无需手动管理流的开闭,避免资源泄漏
内容的提问来源于stack exchange,提问作者Joe Fisher
相关产品推荐
相关产品推荐

