c# - 无法将当前 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"));
解决方案
您的响应显示的是分页结果,因此您的模型需要看起来像这样:
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
}
推荐阅读
- homebrew - 您是否在 Formular 中指定平台/拱门
- php - 是否可以更改二进制发行版的 PHP 配置选项(不是从源代码构建 PHP?)
- node.js - 为什么我的 Node.js 服务在 GraalVM 下意外停止?
- automic - 将 Automic 配置为仅在一定数量的作业失败后发送警报?
- icalendar - 对于依赖于最后(可能较晚)完成时间的事件,是否有类似于 iCalendar RRULE 的标准?
- json - Swift Decodable 预设字段(来自 JSON)
- android - kotlin 中的“NullPointerException:null 不能转换为非 null 类型错误”
- bash - 为什么 if 语句从 bash 脚本中的文件名中删除连接变量?
- apache-kafka - Kafka MQTT Sink 连接器失败,HashMap 不是受支持的类型
- html - 具有不同大小的图像缩略图和上方对齐文本的响应式网格