[英]Cannot deserialize the current JSON object
大家好,整天都在。 无法弄清楚我出了什么问题。 这是我的课:
public class Staff
{
public string FirstName { get; set; }
public string LastName { get; set; }
public object PhoneNumber { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string JobTitle { get; set; }
public string Manager { get; set; }
}
这是调用api的代码:
private List<Staff> getAllStaff()
{
try
{
var resultList = new List<Staff>();
var client = new HttpClient();
var data = client.GetAsync("http://localhost:8000/api/staff").ContinueWith(response =>
{
var result = response.Result;
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
var readResult = result.Content.ReadAsAsync<List<Staff>>();
readResult.Wait();
resultList = readResult.Result;
}
});
data.Wait();
return resultList;
}
catch (Exception ex)
{
throw ex;
}
}
传递给视图的数据:
public ActionResult Index()
{
var staff = getAllStaff();
return View(staff);
}
最后返回了一个json示例:
[ { "FirstName": "xxxx", "LastName": "xxxx", "PhoneNumber": "xxxx", "Email": "xxxx", "UserName": "xxxx", "JobTitle": "xxxx", "Manager": "xxxx" }, { "FirstName": "xxxx", "LastName": "xxxx", "PhoneNumber": "xxxx", "Email": "xxxx", "UserName": "xxxx", "JobTitle": "xxxx", "Manager": "xxxx" }, ]
我不断得到的错误:
无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.Collections.Generic.List`1 [json.Models.Staff]',因为该类型需要JSON数组(例如[1, 2,3])正确反序列化。 要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型)数组或列表),可以从JSON对象反序列化。 还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。
api可能同时返回数组和单个记录。 在这种情况下,您的代码应兼顾两者。 您还要求这些阻止呼叫带来麻烦。 使代码一直保持异步状态。
private async Task<List<Staff>> getAllStaff() {
var resultList = new List<Staff>();
var client = new HttpClient();
var response = await client.GetAsync("http://localhost:8000/api/staff");
if (response.StatusCode == System.Net.HttpStatusCode.OK) {
bool arrayParseFailed = false;
try {
resultList = await response.Content.ReadAsAsync<List<Staff>>();
} catch (Exception ex) {//Array pase failed so try single
arrayParseFailed = true;
}
if (arrayParseFailed) {
try {
var staff = await response.Content.ReadAsAsync<Staff>();
if (staff != null) {
resultList.Add(staff);
}
} catch (Exception ex) {
}
}
}
return resultList;
}
所以现在该动作也应该更新为异步
public async Task<ActionResult> Index() {
var staff = await getAllStaff();
return View(staff);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.