无法反序列化当前的JSON对象,为什么呢? [英] Cannot deserialize the current JSON object, WHY?

查看:2224
本文介绍了无法反序列化当前的JSON对象,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用的WebAPI从我的数据的基础上获得的员工列表,使用这种code:
这是我的客户MVC应用程序的code:

I'm trying to use a WebApi to get a list of Employees from my data base, using this code: This is the code of my client MVC Application:

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

这是我的WebAPI的code:

And this is the code of my WebAPI:

    public IEnumerable<Employee> GetEmployees()
    {
        return db.Employees.AsEnumerable();
    }

但这种错误不断出现,我不明白为什么:

But this error keeps popping up and I can't understand why:

无法反序列化当前的JSON对象(例如{名:值})
  入式'DataAccess.Employee []',因为类型需要一个JSON
  阵列(例如[1,2,3]),以正确的反序列化。要解决这个错误
  要么改变的JSON到一个JSON数组(例如[1,2,3]),或改变
  反序列化类型,以便它是一个正常的.NET类型(例如不是
  基本类型喜欢整数,而不是一个集合类型像数组或
  列表),可以从JSON对象反序列化。
  JsonObjectAttribute也可加入到用它强制类型
  从JSON对象反序列化。路径消息,1号线,11位。

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'DataAccess.Employee[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'Message', line 1, position 11.

我的Employee类:

My Employee Class:

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

JSON的输出我真的不知道如何得到它。

The Json output I'm not really sure how to get it

msg变量的内容:

我的味精变量返回

{\\消息\\:\\出现错误\\,\\ExceptionMessage \\:\\。在'ObjectContent`1类型没有序列化内容类型应用程序/ JSON响应主体; charset=utf-8'.\\\",\\\"ExceptionType\\\":\\\"System.InvalidOperationException\\\",\\\"StackTrace\\\":null,\\\"InnerException\\\":{\\\"Message\\\":\\\"An发生错误\\,\\ExceptionMessage \\:\\型检测自引用循环'System.Data.Entity.DynamicProxies.ProductSubCategory_9EC9A3706390DE6A3B51F713F0DDAC2162AFB5B3FAB8F8587C9A865333A7729A'.路径'[0].Products[0].ProductSubCategory.ProductCategory.ProductSubCategories'.\\\",\\\"ExceptionType\\\":\\\"Newtonsoft.Json.JsonSerializationException\\\",\\\"StackTrace\\\":\\\"在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter作家,对象的值,JsonProperty财产,JsonContract合同,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter作家,IWrappedCollection值, JsonArrayContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter作家,对象的值,JsonObjectContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter作家,对象的值,JsonObjectContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft .Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter作家,对象的值,JsonObjectContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft。 Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter作家,IWrappedCollection值,JsonArrayContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract, JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter作家,对象的值,JsonObjectContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json .Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter作家,IWrappedCollection值,JsonArrayContract合同,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter作家,对象的值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\\ r \\ n在Newtonsoft.Json。 Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter,对象的值)\\ r \\ n在Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter,对象的值)\\ r \\ n在System.Net.Http.Formatting.JsonMediaTypeFormatter&LT;> c__DisplayClassd .b__c(个)\\ r \\ n在System.Threading.Tasks.TaskHelpers.RunSynchronously(动作的动作,令牌的CancellationToken)\\}}

"{\"Message\":\"An error has occurred.\",\"ExceptionMessage\":\"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.\",\"ExceptionType\":\"System.InvalidOperationException\",\"StackTrace\":null,\"InnerException\":{\"Message\":\"An error has occurred.\",\"ExceptionMessage\":\"Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.ProductSubCategory_9EC9A3706390DE6A3B51F713F0DDAC2162AFB5B3FAB8F8587C9A865333A7729A'. Path '[0].Products[0].ProductSubCategory.ProductCategory.ProductSubCategories'.\",\"ExceptionType\":\"Newtonsoft.Json.JsonSerializationException\",\"StackTrace\":\" at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClassd.b__c()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)\"}}"

推荐答案

要阻止发生的历史的错误的最好方法是:

The best way to stop that error from occuring is:

在您的WebAPI项目进入App_Start文件夹,并添加到WebApiConfig code这四行:

In your WebApi project go to the App_Start folder and add to the WebApiConfig this four lines of code:

config.EnableSystemDiagnosticsTracing();
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
config.Formatters.Remove(config.Formatters.XmlFormatter);

和确保你已经instaled JSON的包的NuGet

and make sure you have instaled the Json nuget package

这篇关于无法反序列化当前的JSON对象,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆