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

JSON响应数组访问遇JsonSerializationException:反序列化错误求助

解决JsonSerializationException:对象无法反序列化为List集合的问题

嘿,这个错误我之前踩过坑!问题核心很清晰:你在尝试把一个JSON对象反序列化成List<software>集合,但实际返回的JSON结构是「一个对象包裹着目标数组」,并不是直接的数组格式。

问题出在哪?

  1. 实体类JsonProperty注解错误:你把[JsonProperty("softwares")]加在了name属性上,这完全不对——这个注解应该用来标记包含数组的那个顶级键,而不是单个软件的名称字段。
  2. 反序列化目标类型不匹配:你的代码JsonConvert.DeserializeObject<List<software>>(SoftResponse)期望JSON是[{},{},...]这种纯数组,但实际后端返回的是类似{"softwares": [{},{},...]}的对象结构。

解决方案

方案一:创建根实体类(推荐,更符合面向对象规范)

先定义一个包含软件数组的根类,用来匹配JSON的顶层结构:

public class SoftwareRoot
{
    [JsonProperty("softwares")]
    public List<software> Softwares { get; set; }
}

然后修改反序列化代码,先解析根对象再提取数组:

var rootResponse = JsonConvert.DeserializeObject<SoftwareRoot>(SoftResponse);
SoftInfo = rootResponse.Softwares; // 这里才是你需要的List集合

方案二:直接提取JSON中的数组(无需新增类)

如果不想额外创建类,可以用Newtonsoft.Json的JObject先解析JSON,再提取数组部分反序列化:

using Newtonsoft.Json.Linq;

var jsonObject = JObject.Parse(SoftResponse);
var softwaresJsonArray = jsonObject["softwares"].ToString();
SoftInfo = JsonConvert.DeserializeObject<List<software>>(softwaresJsonArray);

最后修正你的实体类

别忘了把错误的[JsonProperty("softwares")]从name属性上移除,正确的实体类应该是:

public class software
{
    public string name { get; set; }
    public string version { get; set; }
    public string fixVersion { get; set; }
    public string vulnerabilities { get; set; }
}

这样调整后,你的视图里@foreach (var item in Model)就能正常遍历每个软件对象,渲染表格内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:20:44