首页 文章

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

提问于
浏览
2

我正在尝试使用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对象(例如{“name”:“value”})反序列化为类型“DataAccess.Employee []”,因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化 . 要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为普通的.NET类型(例如,不是像整数这样的基本类型,而不是类似的集合类型可以从JSON对象反序列化的数组或List . 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; }
    }
}

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

msg变量内容:

我的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 \“:\”在Newtonsoft.Json . 在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer,IWrappedCollection值,JsonArrayContract Contract ,JsonProperty成员)的Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer,Object value,JsonProperty属性,JsonContract Contract ,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 va lue,JsonObjectContract Contract ,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,Object value) ,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer,Object value,JsonObjectContract contract,JsonProperty mem) ber,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.SerializeList(JsonWriter writer,IWrappedCollection values,JsonArrayContract contract,JsonProperty member,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)在Newtonsoft.Json的Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,Object value,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\ r \ n中的成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\ r \ n . Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer,IWrappedCollection values,JsonArrayContract contract,JsonProperty member,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.Serialize(JsonWriter jsonWriter,Object value)\ r \ n在Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter,Objec) System.Net.Http.Formatting.JsonMediaTypeFormatter . <> c__DisplayClassd.b__c()\ r \ n在System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action,CancellationToken token)\“}} “

2 回答

  • 4

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

    在您的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包

  • 2

    读取错误,“无法将当前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 .

相关问题