【发布时间】: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<UserModel>,但它不是一个列表,它只是一个对象。