首页 > 解决方案 > 无法将当前 JSON 对象(例如 {“name”:“value”})反序列化为类型

问题描述

我的请求如下所示:

{
  "count": 5,
  "pages": 1,
  "result": [
    {
      "id": "00000000-0000-0000-0000-000000000001",
      "orgId": "00000000-0000-0000-0000-000000000111",
      "userName": "SamPowell",
      "firstName": "Sam",
      "lastName": "Powell",
      "password": "tytrtyrty",
      "token": null,
      "badge": "001",
      "defaultLanguage": "english",
      "supervisorId": "00000000-0000-0000-0000-000000000000",
      "inactive": false,
}]
}

反序列化失败

_users = JsonConvert.DeserializeObject<List<ApplicationUser>>_restResponse.Content);

应用程序用户类缺少“计数”和“页数”

如何将其添加到列表中

我需要从对象结果中断言类似下面的内容Assert.IsNotNull(_users[0].userName.Equals("SamPowell"));

标签: c#listdeserializationjson-deserialization

解决方案


您的响应显示的是分页结果,因此您的模型需要看起来像这样:

public class PagedResult<T>
{
    public int count { get; set; }
    public int pages { get; set; }
    public T[] result { get; set; }
}

public class ApplicationUser
{
    public string id { get; set; }
    public string orgId { get; set; }
    public string userName { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string password { get; set; }
    public object token { get; set; }
    public string badge { get; set; }
    public string defaultLanguage { get; set; }
    public string supervisorId { get; set; }
    public bool inactive { get; set; }
}

然后你会像这样反序列化和测试它:

public class Testing
{
    [Test]
    public void Deserialize()
    {
        var page = JsonConvert.DeserializeObject<PagedResult<ApplicationUser>>(json);
        var users = page.result;
        Assert.IsNotNull(users[0].userName.Equals("SamPowell"));
    }    

     private string json = @""; //your json
}

推荐阅读