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

时间:2014-06-09 18:37:57

标签: c# json serialization asp.net-web-api

我尝试使用WebApi从我的数据库中获取Employees列表,使用以下代码: 这是我的客户端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);

这是我的WebAPI的代码:

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

但是这个错误不断出现,我无法理解原因:

  

无法反序列化当前的JSON对象(例如{&#34; name&#34;:&#34; value&#34;})   进入类型&#39; DataAccess.Employee []&#39;因为类型需要JSON   数组(例如[1,2,3])正确反序列化。要修复此错误   要么将JSON更改为JSON数组(例如[1,2,3]),要么更改   反序列化类型,以便它是一个普通的.NET类型(例如,不是   原始类型,如整数,而不是像数组或类似的集合类型   List)可以从JSON对象反序列化。   JsonObjectAttribute也可以添加到类型中以强制它   从JSON对象反序列化。路径&#39;消息&#39;,第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; }
    }
}

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

msg变量内容:

我的msg变量返回

&#34; {\&#34;消息\&#34;:\&#34;发生了错误。\&#34;,\&#34; ExceptionMessage \&#34;:\& #34;&#39; ObjectContent`1&#39;类型无法序列化内容类型的响应主体&#39; application / json;字符集= UTF-8&#39; \&#34; \&#34; ExceptionType \&#34;:\&#34; System.InvalidOperationException \&#34; \&#34;堆栈跟踪\&# 34;:null,\&#34; InnerException \&#34;:{\&#34; Message \&#34;:\&#34;发生错误。\&#34;,\&#34 ; ExceptionMessage \&#34;:\&#34;使用类型&#39; System.Data.Entity.DynamicProxies.ProductSubCategory_9EC9A3706390DE6A3B51F713F0DDAC2162AFB5B3FAB8F8587C9A865333A7729A&#39;检测到自引用循环。路径&#39; [0] .Products [0] .ProductSubCategory.ProductCategory.ProductSubCategories&#39;。\&#34;,\&#34; ExceptionType \&#34;:\&#34; Newtonsoft.Json。 JsonSerializationException \&#34; \&#34;堆栈跟踪\&#34;:\&#34; at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer,Object value,JsonProperty property,JsonContract contract,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer,IWrappedCollection values, JsonArrayContract合约,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty成员,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在Newtonsoft.Json.Seria在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer,Object value,JsonObjectContract contract,JsonProperty成员)中的lization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n ,JsonContainerContract collectionContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization .JsonSerializerInternalWriter.SerializeObject(JsonWriter writer,Object value,JsonObjectContract contract,JsonProperty member,JsonContainerContract collectionContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Seri alizeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer,IWrappedCollection值,JsonArrayContract契约,JsonProperty成员,JsonContainerContract collectionContract, JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (JsonWriter writer,Object value,JsonObjectContract contract,JsonProperty member,JsonContainerContract collectionContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Ob) ject值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer,IWrappedCollection值,JsonArrayContract契约,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\ r \ n \ n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty member,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter,Object值)\ r \ n在Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter,Object value)\ r \ n在System.Net.Http.Formatting.JsonMediaTypeFormatter。&lt;&gt; c__DisplayClassd.b__c()\ r \ n at System.Threading.Tasks.TaskHelpers.RunSynchronously(动作,取消令牌令牌)\&#34;}}&#34;

2 个答案:

答案 0 :(得分:4)

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

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

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

你需要确保上面的“msg”是一个真正的JSONArray。

{ "key" : "Value" }

是一个JSONObject,

[{ "key" : "Value" }]

是一个JSONArray。

答案 1 :(得分:2)

阻止该错误发生的最佳方法是:

在您的WebApi项目中,转到App_Start文件夹并将这四行代码添加到WebApiConfig中:

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

并确保您已经安装了Json nuget包