【问题标题】:Mapping API to Object C#将 API 映射到对象 C#
【发布时间】:2022-01-01 12:13:12
【问题描述】:

我尝试将 API 映射到一个对象,但出现错误:

Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List'1[APIWebApp.Models.UserModel] ' 因为该类型需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。 要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“@count”,第 2 行,位置 11。'

这是我的代码:

运行映射的函数:

public List<UserModel> GetUserList()
        {
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Credentials = new NetworkCredential("un", "pw");
                    webClient.BaseAddress = StaticItems.EndPoint;
                    var json = webClient.DownloadString("userlist?view=expand");
                    var list = JsonConvert.DeserializeObject < List<UserModel>>(json);
                    return list.ToList();
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
        }

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

这是模型:

namespace APIWebApp.Models
{
    public class UserModel
    {
        public int count { get; set; }
        public int start { get; set; }
        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; }
    }
}

API json:

{
  "@count": 2,
  "@start": 1,
  "@totalcount": 2,
  "Messages": [],
  "ResourceName": "user",
  "ReturnCode": 0,
  "content": [
    {"user": {
      "name": "Eric",
      "age": "25",
      "date": "2021-10-23T11:18:10+00:00",
    }},
    {"user": {
      "name": "Paul",
      "age": "30",
      "date": "2021-10-23T11:18:10+00:00",
    }}]
}

如何解决导致错误的原因?

【问题讨论】:

  • 为什么 JSON 属性名称中包含 @ 字符?
  • 您正试图将 JSON 反序列化为 List&lt;UserModel&gt;,但它不是一个列表,它只是一个对象。

标签: c# json api mapping


【解决方案1】:

欢迎! API 返回的 JSON 是 UserModel 而不是 List&lt;UserModel&gt;,因此首先需要将 json 反序列化为 UserModel。然后,您可以从GetUsersList() 返回您喜欢的任何内容,UserModelList&lt;Users&gt;(如下所示)。

using (WebClient webClient = new WebClient())
    {
          webClient.Credentials = new NetworkCredential("un", "pw");
          webClient.BaseAddress = StaticItems.EndPoint;
          var json = webClient.DownloadString("userlist?view=expand");
          UserModel userModel = JsonConvert.DeserializeObject <UserModel>(json); // here
          return userModel.content.Select(c => c.user).ToList();
    }

【讨论】:

    【解决方案2】:

    如果你只需要用户列表,只需返回用户

    public List<User> GetUserList()
            {
                try
                {
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.Credentials = new NetworkCredential("un", "pw");
                        webClient.BaseAddress = StaticItems.EndPoint;
                        var json = webClient.DownloadString("userlist?view=expand");
                        var list = JsonConvert.DeserializeObject<List<UserModel>>(json);
        
                        List<User> userList = new List<User>();
                        foreach (var item in list.content)
                        {
                            userList.Add(item.user);
                        }
                        return userList;
                    }
                }
                catch (WebException ex)
                {
                    throw ex;
                }
            }
    

    【讨论】:

      【解决方案3】:

      请更改您的(UserModel) 模型类

      你的模型类

      public class UserModel
      {
          public int count { get; set; }
          public int start { get; set; }
          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 UserModel
      {
          public int count { get; set; }
          public int start { get; set; }
          public int totalcount { get; set; }
          public List<object> Messages { get; set; }
          public string ResourceName { get; set; }
          public int ReturnCode { get; set; }
          public List<Content> content { get; set; }
      }
      

      这将正确地反序列化对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-04
        • 1970-01-01
        • 2019-05-27
        • 2012-04-16
        • 2010-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多