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

如何在未知结构的情况下解析嵌套JSON

解析嵌套JSON的实现方案

你当前的代码只能处理非嵌套的JSON属性,遇到嵌套对象(比如示例里的name字段)时,直接转字符串会得到{ "first": "NJ" }这样的结果,无法提取内部的键值对。要动态获取嵌套JSON的所有值,需要用递归遍历的方式处理每个层级的JSON元素。

原代码

using System;
using Newtonsoft.Json.Linq;

public class Program
{
    public static void Main()
    {
        string json = @"
        [ 
            {""name"":{""first"":""NJ""} ,""age"":45}
        ]";
        
        JArray a = JArray.Parse(json);
        
        foreach (JObject o in a.Children<JObject>())
        {
            foreach (JProperty p in o.Properties())
            {
                string name = p.Name;
                string value = (string)p.Value;
                Console.WriteLine(name + " -- " + value);
            }
        }
    }
}

修改后的递归实现代码

using System;
using Newtonsoft.Json.Linq;

public class Program
{
    public static void Main()
    {
        string json = @"
        [ 
            {""name"":{""first"":""NJ""} ,""age"":45, ""contacts"": {""email"": ""nj@example.com"", ""phone"": [""123456"", ""789012""]}}
        ]";
        
        JArray a = JArray.Parse(json);
        // 遍历数组中的每个对象
        foreach (JToken token in a.Children())
        {
            TraverseJson(token);
        }
    }

    // 递归遍历JSON元素的方法
    private static void TraverseJson(JToken token, string parentPath = "")
    {
        switch (token.Type)
        {
            // 处理JSON对象
            case JTokenType.Object:
                foreach (JProperty prop in token.Children<JProperty>())
                {
                    // 拼接当前属性的路径,方便区分嵌套层级
                    string currentPath = string.IsNullOrEmpty(parentPath) ? prop.Name : $"{parentPath}.{prop.Name}";
                    TraverseJson(prop.Value, currentPath);
                }
                break;
            // 处理JSON数组
            case JTokenType.Array:
                int index = 0;
                foreach (JToken arrayItem in token.Children())
                {
                    string arrayPath = $"{parentPath}[{index}]";
                    TraverseJson(arrayItem, arrayPath);
                    index++;
                }
                break;
            // 处理普通值类型(字符串、数字、布尔等)
            default:
                Console.WriteLine($"{parentPath} -- {token.ToString()}");
                break;
        }
    }
}

代码说明

  • 递归遍历:通过TraverseJson方法递归处理每个JSON元素,根据元素类型(对象、数组、普通值)执行不同逻辑。
  • 路径追踪:通过parentPath参数记录当前元素的层级路径,输出时能清晰看到嵌套关系(比如name.first、contacts.phone[0])。
  • 兼容所有类型:不仅能处理嵌套对象,还能解析数组类型的嵌套结构,覆盖更多JSON场景。

运行上述代码后,输出结果为:

name.first -- NJ
age -- 45
contacts.email -- nj@example.com
contacts.phone[0] -- 123456
contacts.phone[1] -- 789012

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:45:06