如何使用LINQ遍历JsonArray?JsonNode调用Select报错求助
问题:使用LINQ遍历JsonNode中的JsonArray报错
JSON数据
{ "dimensions": [ { "name": "dim1" }, { "name": "dim2" }, { "name": "dim3" } ] }
加载JSON的C#代码
JsonObject root = JsonNode.Parse(jsonString)?.AsObject();
错误的遍历代码
尝试用LINQ遍历dimensions数组时,编写了如下代码:
var list = root["dimensions"].GetEnumerator().Select(p => p["name"].GetValue).ToArray();
报错信息
CS1061: 'IEnumerator<JsonNode?>' does not contain a definition for 'Select' and no accessible extension method 'Select' accepting a first argument of type 'IEnumerator<JsonNode?>' could be found (are you missing a using directive or an assembly reference?)
疑问:JsonNode是否支持LINQ?为什么相关搜索结果很少?
解答
错误原因
GetEnumerator()返回的是IEnumeratorSelect等扩展方法仅对IEnumerable
JsonNode完全支持LINQ
JsonNode是.NET 6+引入的System.Text.Json新API,完全兼容LINQ,只是你用错了遍历方式。以下是两种正确写法:
写法1:转为JsonArray后使用LINQ
using System.Linq; var dimensionsArray = root["dimensions"]?.AsArray(); var nameList = dimensionsArray? .Select(node => node["name"]?.GetValue<string>()) .ToArray();
写法2:直接转为IEnumerable
using System.Linq; var dimensions = root["dimensions"] as IEnumerable<JsonNode>; var nameList = dimensions? .Select(node => node["name"]?.GetValue<string>()) .ToArray();
关键注意点
- 必须添加
using System.Linq;命名空间,否则LINQ扩展方法无法识别; GetValue<T>()需要指定具体类型(如string),否则返回object类型;- 全程使用
?.空安全操作符,避免空引用异常; - 确保项目目标框架为.NET 6或更高版本,JsonNode才会被支持。
关于资料少的问题
JsonNode属于较新的API,相比老牌的Newtonsoft.Json,社区内容积累确实较少,但官方文档已经覆盖了所有核心用法,且其设计完全兼容LINQ等.NET常用特性,不存在“不支持”的情况。
内容的提问来源于stack exchange,提问作者Chris Harrington
相关产品推荐
相关产品推荐

