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

C#如何读取JSON文件并统计指定嵌套子对象的数量

问题错误点
  • 层级定位错误:没有按照JSON的实际嵌套路径查找节点,subfunction节点不是根节点的直接子节点,完整路径为根节点 > Y > functiongroup > 各function节点 > subfunction
  • 类型转换错误:subfunction是JSON对象(键值对结构),不是JSON数组,强制转换为JArray会得到null,后续调用Count会触发空引用异常
正确实现代码

首先通过NuGet安装Newtonsoft.Json依赖包,再使用如下代码:

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

class Program
{
    static void Main()
    {
        // 读取JSON文件内容
        string jsonContent = File.ReadAllText(@"你的JSON文件实际路径");
        JObject root = JObject.Parse(jsonContent);
        
        // 定位到functiongroup节点
        JObject functionGroup = root["Y"]?["functiongroup"] as JObject;
        if (functionGroup == null)
        {
            Console.WriteLine("未找到functiongroup节点");
            return;
        }

        List<int> counts = new List<int>();
        // 遍历functiongroup下所有function节点
        foreach (var functionProp in functionGroup.Properties())
        {
            JObject functionNode = functionProp.Value as JObject;
            JObject subFunction = functionNode?["subfunction"] as JObject;
            // 统计subfunction下的子对象数量,节点不存在时计数为0
            int subCount = subFunction?.Count ?? 0;
            counts.Add(subCount);
        }

        // 按要求格式输出结果
        Console.WriteLine(string.Join(", ", counts));
    }
}
输出结果

对应你提供的JSON结构,运行后输出为:1, 3, 3, 4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:45:00