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

C#中解析JSON文件为JsonArray对象报错,求解决方法

解决办法

错误原因是你混用了两个不同的JSON处理库:Newtonsoft.Json(Json.NET)和System.Text.Json。JsonConvert.DeserializeObject属于Newtonsoft的API,而JsonArray是System.Text.Json.Nodes命名空间下的类型,两者不兼容,导致无法找到合适的构造函数进行反序列化。

下面提供两种可行方案:

方案一:继续使用Newtonsoft.Json,改用JArray类型

Newtonsoft.Json有自己的JSON数组类型JArray,替换JsonArray即可正常解析:

using Newtonsoft.Json.Linq;
using System.IO;

string jsonContent = File.ReadAllText(JsonFilePath);
JArray list = JArray.Parse(jsonContent);

访问数组元素示例:

// 获取第一个对象的id和first_name
int firstId = (int)list[0]["id"];
string firstName = (string)list[0]["first_name"];

方案二:改用System.Text.Json库解析

如果坚持使用System.Text.Json.Nodes.JsonArray,需要用System.Text.Json的API来完成解析:

using System.Text.Json.Nodes;
using System.IO;

string jsonContent = File.ReadAllText(JsonFilePath);
JsonArray list = JsonNode.Parse(jsonContent).AsArray();

访问数组元素示例:

// 获取第二个对象的last_name
string lastName = (string)list[1]["last_name"];

注意事项

  • 使用Newtonsoft.Json时,需确保项目已安装Newtonsoft.Json NuGet包;
  • 使用System.Text.Json时,.NET Core 3.0+、.NET 5及以上版本默认内置该库,无需额外安装。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:01:44