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

C#使用Newtonsoft.Json反序列化API JSON到List<UserModel>报错如何解决

错误根源

你遇到的反序列化错误由两个问题导致:

  • API返回的JSON根节点是单个对象,不是数组,你尝试直接反序列化为List<UserModel>集合类型,类型不匹配触发报错。
  • 你定义的UserModel中count/start/totalcount三个属性名,和JSON中带@前缀的键名@count/@start/@totalcount不匹配,就算反序列化成功也拿不到对应字段的值。

修复方案

1. 调整模型属性映射

给UserModel中对应带@前缀的JSON键的属性添加JsonProperty特性,指定映射关系:

using Newtonsoft.Json; // 需引入Newtonsoft.Json命名空间

namespace APIWebApp.Models
{
    public class UserModel
    {
        [JsonProperty("@count")]
        public int count { get; set; }
        [JsonProperty("@start")]
        public int start { get; set; }
        [JsonProperty("@totalcount")]
        public int totalcount { get; set; }
        public object[] Messages { get; set; }
        public string ResourceName { get; set; }
        public int ReturnCode { get; set; }
        public Content[] content { get; set; }
    }
    
    public class Content
    {
        public Users user { get; set; }
    }

    public class Users
    {
        public string name { get; set; }
        public string age { get; set; }
        public string date { get; set; }
    }
}

2. 修改反序列化逻辑

首先将JSON反序列化为单个UserModel对象,再根据业务需要提取数据:
如果你的方法目的是返回用户列表,调整代码如下:

public List<Users> GetUserList()
{
    try
    {
        using (WebClient webClient = new WebClient())
        {
            webClient.Credentials = new NetworkCredential("un", "pw");
            webClient.BaseAddress = StaticItems.EndPoint;
            var json = webClient.DownloadString("userlist?view=expand");
            // 先反序列化为单个UserModel包裹对象
            var result = JsonConvert.DeserializeObject<UserModel>(json);
            // 提取content数组中的所有user对象返回
            return result.content.Select(c => c.user).ToList();
        }
    }
    catch (WebException ex)
    {
        throw ex;
    }
}

public static class StaticItems
{
    public static string EndPoint = "https://XXXXXX";
}

如果你需要保留接口返回的分页总数、返回码等元数据,直接将方法返回值改为UserModel,返回反序列化得到的result对象即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:45:07