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

C#递归JSON解析与遍历问题:类型转换与深度遍历求助

递归JSON反序列化与遍历问题

我翻遍了平台上所有递归JSON相关内容,没找到匹配当前真正递归场景的方案。现在碰到两个技术难题:

  • 用Newtonsoft.JSON反序列化深度达200的递归JSON时,因为末尾的"from"字段是整数(值为49),而非定义的from对象,抛出Int64类型转换错误;
  • 不知道如何遍历该递归JSON中的所有"recursive"元素。

相关代码与错误信息

JSON示例

{
    "schema": [
        {
            "@id": 1,
            "recursive": [
                {
                    "@Id": 2,
                    "from": {
                        "@id": 1,
                        "recursive": [
                            {
                                "@Id": 2,
                                "from": {
                                    "@id": 1,
                                    "recursive": [
                                        {
                                            "@Id": 2,
                                            "from" : 49
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        }
    ]
}

C#实体类

public class rootSchema
{
        [JsonProperty("@id")]
        public int @id { get; set; }

        [JsonProperty("recursive")]
        public List<recursive> recursive { get; set; }
}
public class from
{
        [JsonProperty("@id")]
        public int @id { get; set; }

        [JsonProperty("recursive")]
        public List<recursive> recursive { get; set; }
}
public class recursive
{
        [JsonProperty("from")]
        public from from { get; set; }

        [JsonProperty("recursive")]
        public List<recursive> recursive { get; set; }
}

错误信息

Newtonsoft.Json.JsonSerializationException: 
'Error converting value 49 to type 'Proj.recursive.from'. Path
'recursive[0].from.recursive[0].from.recursive[0].from.recursive[0]
.from.recursive[0].from.recursive[0].from.recursive[0].from.recursive[0]
.from.recursive[0].from.recursive[0].from.recursive[0].from.recursive[0]
.from.recursive[0].from.recursive[0].from.recursive[0].from.recursive[0]
.from.recursive[0].from.recursive[0].from.recursive[0].from.recursive[0]
.from.recursive[0].from.recursive[0].from.recursive[0].from.recursive[0]
.from.recursive[0].from', line 1, position 16273.'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:31:00