You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#序列化TransactionLogs类到JSON文件报空引用异常如何解决

空引用异常修复

根因

你实例化TransactionLogs类后,其transLogs列表属性未做初始化,默认值为null,直接遍历该属性就会触发空引用异常。同时原有逻辑存在偏差:当前场景是新增一条交易日志,无需遍历现有列表,应该直接构造新的日志对象添加到列表中。

修复步骤

  1. 给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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:24:04