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

在C#中使用Newtonsoft获取JSON的total_count数据方法咨询

获取JSON中的total_count数据

嘿,顺着你现有的代码逻辑往下走就能拿到total_count啦!咱们先理清楚这个JSON的层级结构:外层data数组的每个元素里,包含了members对象,而total_count就藏在members下的summary对象里。

你可以在遍历外层data的循环里,直接通过键名逐层访问:

JObject results = JObject.Parse(json);
foreach (var result in results["data"])
{
    // 你原来获取name的代码
    string name_dt = (string)result["name"];
    
    // 获取total_count,直接逐层访问对应键
    int totalCount = (int)result["members"]["summary"]["total_count"];
    
    // 如果成员总数可能很大(比如超过int的最大值),换成long类型更稳妥
    // long totalCount = (long)result["members"]["summary"]["total_count"];
}

安全获取的小技巧

如果担心JSON结构可能存在缺失(比如某个键不存在),可以用空条件运算符?.和Value<T>方法来避免空引用异常:

JObject results = JObject.Parse(json);
foreach (var result in results["data"])
{
    string name_dt = (string)result["name"];
    
    // 安全获取,返回可空int,不存在时为null
    int? totalCount = result["members"]?["summary"]?["total_count"]?.Value<int>();
    
    if (totalCount.HasValue)
    {
        // 处理有效数值
        Console.WriteLine($"成员总数:{totalCount.Value}");
    }
    else
    {
        // 处理键不存在的情况
        Console.WriteLine("未能获取成员总数");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:29:53