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

C#读写嵌套JSON数据及类型转换报错问题解决方法

问题根因

两个核心问题导致报错和解析失败:

  1. 外层类定义和JSON结构不匹配:你的JSON根节点不是带固定Status属性的对象,是键为自定义名称(ConfigError/FileCopyError)、值为状态对象的键值对集合,自定义的SummaryEmailClass完全不符合结构,不需要使用。
  2. 类型转换缺失:用dynamic接收反序列化结果时,通过键取到的是Newtonsoft.Json内置的JObject类型,没有做显式转换,无法直接赋值给自定义的SummaryEmailStatus类型。
读取指定键对象的实现

直接将根节点反序列化为Dictionary<string, SummaryEmailStatus>即可完美匹配结构,不需要额外定义外层类,通用方法代码如下:

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;

public static SummaryEmailStatus ReadTargetStatus(string jsonFilePath, string objectKey)
{
    string jsonContent = File.ReadAllText(jsonFilePath);
    // 直接反序列化为键值对字典,强类型校验更稳定
    Dictionary<string, SummaryEmailStatus> statusDict = 
        JsonConvert.DeserializeObject<Dictionary<string, SummaryEmailStatus>>(jsonContent);
    
    if (!statusDict.ContainsKey(objectKey))
        throw new KeyNotFoundException($"JSON中不存在指定键:{objectKey}");
    
    return statusDict[objectKey];
}

如果一定要保留原来的dynamic写法,只需要加显式类型转换即可解决报错,但不推荐动态写法,运行时出错概率更高:

// 动态写法的修正版
dynamic jsonFile = JsonConvert.DeserializeObject(File.ReadAllText(jsonFilePath));
SummaryEmailStatus sumclass = jsonFile[objectKey].ToObject<SummaryEmailStatus>();
更新字段并写回JSON的实现

读取全量数据为强类型字典后,直接修改对应对象的属性,再序列化写回文件即可,示例代码:

public static void UpdateAndSaveStatus(string jsonFilePath, string objectKey, bool newIsSentStatus)
{
    string jsonContent = File.ReadAllText(jsonFilePath);
    Dictionary<string, SummaryEmailStatus> statusDict = 
        JsonConvert.DeserializeObject<Dictionary<string, SummaryEmailStatus>>(jsonContent);
    
    // 不存在对应键时直接新增条目
    if (!statusDict.ContainsKey(objectKey))
        statusDict[objectKey] = new SummaryEmailStatus();
    
    // 更新字段值
    SummaryEmailStatus target = statusDict[objectKey];
    target.DateSent = DateTime.Now; // 按需使用UTC时间或本地时间即可
    target.IsSent = newIsSentStatus;
    // ToolType字段按需更新即可

    // 序列化时带缩进,方便后续人工查看编辑
    string updatedJson = JsonConvert.SerializeObject(statusDict, Formatting.Indented);
    File.WriteAllText(jsonFilePath, updatedJson);
}
补充说明
  • 用字典作为根节点反序列化的方案灵活性更好,后续新增其他错误类型的状态条目时,不需要修改任何类定义,直接传入新的键名就能正常读写。
  • 对于这类本地小配置存储场景,JSON完全够用,不需要更换其他方案;如果存在多进程/多线程同时读写文件的场景,读写时加个文件锁避免文件损坏即可。

内容的提问来源于stack exchange,提问作者Datboydozy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 21:36:25