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

C#中JToken转自定义数组类型报错求助

解决C#中JToken转自定义类数组的报错问题

我太懂刚学C#踩坑的憋屈感了,你遇到的这个报错其实很好解决——核心问题是currentPeople["people"]返回的是JToken类型,它本身没有ToArray<T>()方法,而Linq的Enumerable.ToArray又要求接收IEnumerable类型的参数,所以才会抛出这个错误。

先理下你的场景:你定义了PersonAttributes和SavedPeople两个类,想把解析后的JObject里的people字段转成PersonAttributes[],但直接调用ToArray<PersonAttributes>()走不通。

两种修正方案

这里有两个简单直接的办法,都能顺利把JToken转成你需要的数组:

方法一:先转JArray再用ToObject序列化

因为currentPeople["people"]本身是数组结构,先把它转换成JArray,再用ToObject<T>()方法直接转成目标数组,同时还能处理空值避免异常:

var people = new SavedPeople();
var currentPeople = JObject.Parse(foundPeople);
people.maxAllowed = (int)currentPeople["maxAllowed"];

// 先转JArray,再转成PersonAttributes数组,空值时返回空数组
var peopleJArray = currentPeople["people"] as JArray;
people.people = peopleJArray?.ToObject<PersonAttributes[]>() ?? Array.Empty<PersonAttributes>();

方法二:用JsonConvert直接反序列化

如果你习惯用Newtonsoft.Json的JsonConvert类,也可以把JToken转成字符串后再反序列化:

var people = new SavedPeople();
var currentPeople = JObject.Parse(foundPeople);
people.maxAllowed = (int)currentPeople["maxAllowed"];

people.people = JsonConvert.DeserializeObject<PersonAttributes[]>(currentPeople["people"].ToString());

小提醒

记得处理空值情况!比如如果currentPeople["people"]是null,方法一里的?.和??会帮你返回一个空数组,后续遍历的时候就不会触发空引用异常啦。

内容的提问来源于stack exchange,提问作者Wede Asmera Tseada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:28:48