【问题标题】:Cannot deserialize the current JSON object, WHY?无法反序列化当前的 JSON 对象,为什么?
【发布时间】:2014-07-30 08:54:10
【问题描述】:

我正在尝试使用 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);

这是我的 WebAPI 的代码:

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

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

无法反序列化当前 JSON 对象(例如 {"name":"value"}) 进入类型“DataAccess.Employee[]”,因为该类型需要 JSON 数组(例如 [1,2,3])以正确反序列化。修复此错误 将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改 反序列化类型,使其成为普通的 .NET 类型(例如,不是 像整数这样的原始类型,而不是像数组这样的集合类型或 List) 可以从 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; }
    }
}

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”的自引用循环。 Newtonsoft.Json 的路径 '[0].Products[0].ProductSubCategory.ProductCategory.ProductSubCategories'.\",\"ExceptionType\":\"Newtonsoft.Json.JsonSerializationException\",\"StackTrace\":\"。 Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer,对象值,JsonProperty 属性,JsonContract 合同,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 member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n 在 Newtonsoft.Json.Serialization .JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, O对象值、JsonObjectContract 合同、JsonProperty 成员、JsonContainerContract 集合合同、JsonProperty containerProperty)\r\n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, 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 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 成员、JsonContainerContract collectionContract、JsonProperty containerProperty)\r\n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, 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 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, JsonContain erContract collectionContract, JsonProperty containerProperty)\r\n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, 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 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 value)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)\r\n r\n 在 System.Net.Http.Formatting.JsonMediaTypeFormatter.c__DisplayClassd.b__c()\r\n 在 System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)\"}}"

【问题讨论】:

  • 第一件事:将WebAPI部分与客户端部分分开;获取 JSON 并检查它是否有意义。如果确实如此,请将其硬编码到一个小的客户端程序中以隔离只是这个问题。
  • 能不能把无法反序列化的JSON输出贴出来?
  • 向我们展示您的 JSON 和您的 Employee
  • 如果返回的 JSON 似乎是单个对象的表示,而不是员工数组。
  • 我更新了帖子,所以它有员工类....Json 我不知道从哪里得到它

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


【解决方案1】:

读取错误;

无法反序列化当前 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。

【讨论】:

  • 你能告诉我该怎么做吗?我对 MVC 和 C# 真的很陌生,对此我很困惑
  • 问题是我在这个项目中没有任何控制台应用程序。这是一个“学校”项目......并且使用完全相同的代码,我的另一个同学可以反序列化 json 而没有任何问题
  • 您需要确保localhost:1411/api/EmployeeAPI 向您返回正确的数据。您的代码按预期工作,它将一组 Employee JSON 对象解析为 Employee c# 类。如果这不是您想要的,那么您需要考虑将其设为非数组。
  • 这正是我想要的......我只是不确定为什么 localhost:1411/api/EmployeeAPI 没有返回 IEnumerable......也许与我的数据库有关?
【解决方案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 包

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多