![](/img/trans.png)
[英]Cannot deserialize the current JSON object (e.g. {“name”:“value”}) into type requires a JSON array (e.g. [1,2,3]) to deserialize correctly
[英]Cannot deserialize the current JSON object (e.g. {“name”:“value”}) into type
我的要求如下所示:
{
"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
}
您明確告訴它要反序列化到ApplicationUser對象類型的列表。 明確地說,您還承認對象ApplicationUser具有與json字符串不同的屬性:
“應用程序用戶類缺少“計數”和“頁面”如何將其添加到列表中”
_users = JsonConvert.DeserializeObject> _restResponse.Content);
你要么必須
創建一個新類,其中包括屬性和“應用程序用戶”列表
要么
(可能是我看到的您正在編寫自動化測試的最有可能的路徑,因此您可能沒有擔任mod類的角色),您需要使用Newtonsoft動態對象進行解析,如下所示:
dynamic d = JObject.Parse("{'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,}]}");
Console.WriteLine(d.result[0].userName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.