简体   繁体   English

无法反序列化当前JSON对象

[英]Cannot deserialize the current JSON object

Sup guys, been on this all day. 大家好,整天都在。 can't figure out what i'm getting wrong. 无法弄清楚我出了什么问题。 here's my class: 这是我的课:

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; }

}

here's the code that calls the api: 这是调用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;
        }
    }

The data being passed to the view: 传递给视图的数据:

public ActionResult Index()
    {
        var staff = getAllStaff();


        return View(staff);
    }

And finally a sample of the json returned: 最后返回了一个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" }, ] 

The error I keep getting: 我不断得到的错误:

Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[json.Models.Staff]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. 无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.Collections.Generic.List`1 [json.Models.Staff]',因为该类型需要JSON数组(例如[1, 2,3])正确反序列化。 To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. 要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型)数组或列表),可以从JSON对象反序列化。 JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. 还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。

It is possible that the api is returning both arrays and single records. api可能同时返回数组和单个记录。 You code should cater for both if that is the case. 在这种情况下,您的代码应兼顾两者。 You are also asking for trouble with those blocking calls. 您还要求这些阻止呼叫带来麻烦。 Make the code async all the way. 使代码一直保持异步状态。

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;
}

So now the action should also be updated to be async 所以现在该动作也应该更新为异步

public async Task<ActionResult> Index() {
    var staff = await getAllStaff();
    return View(staff);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM