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

如何遍历含嵌套数组的JSON响应 解决C#解析内层元素为空问题

Unity嵌套JSON数组反序列化获取最内层元素为null的解决方案

序列化类定义问题

针对Unity自带JsonUtility的要求:

  • 所有层级的自定义类都必须添加[Serializable]特性,包括嵌套数组的元素类
  • 所有需要序列化的字段必须为public修饰,或者添加[SerializeField]特性
  • 字段名必须和JSON返回的key完全匹配,区分大小写
  • 支持数组和List<T>作为集合类型,不要将数组类型定义为单个对象
    正确示例:
    using System;
    [Serializable]
    public class ApiResponseRoot
    {
        public OuterItem[] outer_data;
    }
    
    [Serializable]
    public class OuterItem
    {
        public InnerItem[] inner_data;
    }
    
    [Serializable]
    public class InnerItem
    {
        public string[] hex_strings;
    }
    

针对Newtonsoft Json for Unity的要求:

  • 无需强制添加[Serializable]特性
  • 如果C#字段/属性名和JSON key不匹配,需要添加[JsonProperty("JSON对应key名称")]特性映射
  • 默认支持属性序列化,如果用私有字段需要加[JsonProperty]特性

层级遍历逻辑问题

  • 遍历前先打印完整JSON文本和反序列化后的各层级对象状态,确认没有跳过某层嵌套结构
  • 每一层遍历前先判断数组是否为null、长度是否大于0,避免空引用异常同时排查哪一层解析失败
    示例遍历逻辑:
    var root = JsonUtility.FromJson<ApiResponseRoot>(apiResponseText);
    if(root.outer_data == null || root.outer_data.Length == 0)
    {
        Debug.LogError("外层数组解析失败");
        return;
    }
    foreach(var outer in root.outer_data)
    {
        if(outer.inner_data == null || outer.inner_data.Length == 0)
        {
            Debug.LogError("中层数组解析失败");
            continue;
        }
        foreach(var inner in outer.inner_data)
        {
            if(inner.hex_strings == null || inner.hex_strings.Length == 0)
            {
                Debug.LogError("内层十六进制数组解析失败");
                continue;
            }
            foreach(var hex in inner.hex_strings)
            {
                Debug.Log($"十六进制字符串:{hex}");
            }
        }
    }
    

特殊场景处理

  • 如果API返回的JSON根节点就是数组,JsonUtility无法直接解析,需要手动在外层套一层对象结构再反序列化
  • 确认最内层的十六进制字段在JSON中是字符串类型,如果是数值类型,定义为string会导致解析为null,可先转为数值再格式化十六进制字符串
  • 反序列化时添加错误捕获,查看具体解析报错:
    // Newtonsoft Json错误捕获示例
    try
    {
        var result = JsonConvert.DeserializeObject<ApiResponseRoot>(apiResponseText);
    }
    catch(Exception ex)
    {
        Debug.LogError($"反序列化报错:{ex.Message}");
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 23:15:04