无法反序列化当前JSON对象,为什么?

Fra*_*ito 3 c# serialization json asp.net-web-api

我正在尝试使用WebApi使用以下代码从数据库中获取员工列表:这是我的客户端MVC应用程序的代码:

        string u = "http://localhost:1411/api/EmployeeAPI";
        Uri uri = new Uri(u);

        HttpClient httpClient = new HttpClient();

        Task<HttpResponseMessage> response = httpClient.GetAsync(uri);

        Task.WaitAll(response);

        HttpResponseMessage resposta = response.Result;

        var msg = resposta.Content.ReadAsStringAsync().Result;

        Employee[] employees = JsonConvert.DeserializeObject<Employee[]>(msg);

        return View(employees);
Run Code Online (Sandbox Code Playgroud)

这是我的WebAPI的代码:

    public IEnumerable<Employee> GetEmployees()
    {
        return db.Employees.AsEnumerable();
    }
Run Code Online (Sandbox Code Playgroud)

但是这个错误不断弹出,我不明白为什么:

无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'DataAccess.Employee []',因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型。数组或列表),可以从JSON对象反序列化。还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。路径“消息”,第1行,位置11。

我的员工班级:

namespace DataAccess
{
    using System;
    using System.Collections.Generic;

    public partial class Employee
    {
        public Employee()
        {
            this.Products = new HashSet<Product>();
        }

        public int EmployeeId { get; set; }
        public string Title { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public byte[] rowguid { get; set; }
        public System.DateTimeOffset ModifiedDate { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

Json输出我不太确定如何获得它

msg变量内容:

我的味精变量返回

“ {\” Message \“:\”发生了一个错误。\“,\” ExceptionMessage \“:\”“ ObjectContent`1”类型无法序列化内容类型为'application / json;的响应主体;charset = utf-8'。\“,\” ExceptionType \“:\” System.InvalidOperationException \“,\” StackTrace \“:null,\” InnerException \“:{\” Message \“:\”错误有\“,\” ExceptionMessage \“:\”检测到类型为'System.Data.Entity.DynamicProxies.ProductSubCategory_9EC9A3706390DE6A3B51F713F0DDAC2162AFB5B3FAB8F8587C9A865333A7729A'的自引用循环。路径'[0] .Products [0] .ProductSubCategory.ProductCategory.ProductSubCategories'。\“,\” ExceptionType \“:\” Newtonsoft.Json.JsonSerializationException \“,\” StackTrace \“:\”

Pat*_*k M 5

读取错误“无法反序列化当前JSON对象(例如{“ name”:“ value”})为类型'DataAccess.Employee []',因为该类型需要一个JSON数组(例如[1,2,3])来正确反序列化。”

 var msg = resposta.Content.ReadAsStringAsync().Result;

 Employee[] employees = JsonConvert.DeserializeObject<Employee[]>(msg);
Run Code Online (Sandbox Code Playgroud)

您需要确保“ msg”上方是实际的JSONArray。

{ "key" : "Value" }
Run Code Online (Sandbox Code Playgroud)

是一个JSONObject,

[{ "key" : "Value" }]
Run Code Online (Sandbox Code Playgroud)

是一个JSONArray。