c# - 复杂对象的Json.Net反序列化——包含基类作为属性的基类

标签 c# asp.net-web-api json.net json-deserialization

几个小时以来,我一直在尝试解决这个问题。我尝试了很多方法并阅读了很多帖子。我似乎找不到解决办法。

我有一个对象层次结构,其中我有包含另一个派生类型的派生类型。我正在使用 Json.Net 的 TypeNameHandling 设置。我在序列化和反序列化时都将其设置为 Auto

生成的 JSON 是:

"[\r\n  {\r\n    \"$type\": \"Common.Monitors.HeartbeatMonitor, Common\",\r\n    \"ClassName\": \"HeartbeatMonitor\",\r\n    \"ServerGroupMonitorId\": 1,\r\n    \"Instructions\": {\r\n      \"$type\": \"Common.Monitors.HeartbeatMonitorInstructions, Common\",\r\n      \"RunIntervalInMinutes\": 1\r\n    },\r\n    \"LastExecutionDateTime\": \"2016-03-22T16:35:18.7458519\"\r\n  },\r\n  {\r\n    \"$type\": \"Common.Monitors.DiskSpaceMonitor, Common\",\r\n    \"ClassName\": \"DiskSpaceMonitor\",\r\n    \"ServerGroupMonitorId\": 2,\r\n    \"Instructions\": {\r\n      \"$type\": \"Common.Monitors.DiskSpaceMonitorInstructions, Common\",\r\n      \"DriveLetter\": \"C:\\\",\r\n      \"AlertWhenPercentFreeLessThan\": 20,\r\n      \"RunIntervalInMinutes\": 30\r\n    },\r\n    \"LastExecutionDateTime\": \"2016-03-22T16:15:18.7458519\"\r\n  }\r\n]"

尝试使用以下反序列化时:

string json = response.Content.ReadAsStringAsync().Result;

IEnumerable<MonitorBase> monitors = JsonConvert.DeserializeObject<IEnumerable<MonitorBase>>(json, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto
            });

我收到以下异常:

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code.

Additional information: Error converting value

"[
   {
     "$type": "Common.Monitors.HeartbeatMonitor, Common",
     "ClassName": "HeartbeatMonitor",
     "ServerGroupMonitorId": 1,
     "Instructions": {
       "$type": "Common.Monitors.HeartbeatMonitorInstructions, Common",
       "RunIntervalInMinutes": 1
     },
     "LastExecutionDateTime": "2016-03-22T16:35:18.7458519"
   },
   {
     "$type": "Common.Monitors.DiskSpaceMonitor, Common",
     "ClassName": "DiskSpaceMonitor",
     "ServerGroupMonitorId": 2,
     "Instructions": {
       "$type": "Common.Monitors.DiskSpaceMonitorInstructions, Common",
       "DriveLetter": "C:\\",
       "AlertWhenPercentFreeLessThan": 20,
       "RunIntervalInMinutes": 30
     },
     "LastExecutionDateTime": "2016-03-22T16:15:18.7458519"
   }
]" 

to type 'System.Collections.Generic.IEnumerable`1[Common.Monitors.MonitorBase]'. Path '', line 1, position 943.

HeartbeatMonitorDiskSpaceMonitor 类型派生自 MonitorBase,它们各自的 Instructions 类型派生自 MonitorInstructionBase

我忍不住假设我遗漏了一些明显的东西,因为我无法想象这不是一个相当普遍的场景。

最佳答案

我认为问题可能出在您的 JSON 是双重序列化的,转义引号 \" 证明了这一点, 可见的换行符 \r\n以及引用整个 JSON 的事实。当你反序列化双序列化的 JSON 时,结果是一个字符串,而不是一个对象,这显然不能转换为 IEnumerable<T>。任何形式的。因此错误。

如果您控制 JSON 的来源,请确保您只序列化对象一次。该问题的一个常见原因是没有意识到某些框架(例如 Web API)会自动为您执行序列化,因此如果您在返回对象之前首先手动序列化对象,那么您最终会得到双重序列化的 JSON。

如果您不控制 JSON 的来源,和/或您无法让所有者修复它,那么您可以通过反序列化 JSON 两次在客户端纠正它:首先获取“真正的”JSON字符串,然后第二个从中生成你的对象。例如:

string escapedJson = response.Content.ReadAsStringAsync().Result;

string realJson = JsonConvert.DeserializeObject<string>(escapedJson);

IEnumerable<MonitorBase> monitors = 
    JsonConvert.DeserializeObject<IEnumerable<MonitorBase>>(realJson, 
        new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto
        });

编辑

我从您的评论中看到您正在手动序列化您的对象以便使用 Json.Net 的 TypeNameHandling 设置,并且您正在寻找一种避免双重序列化的方法。

你基本上有两个选择:

  1. 添加TypeNameHandling设置为 Web API 的全局序列化设置,并从您的方法中删除手动序列化代码。为此,请在 Application_Start() 中添加以下内容global.asax 中的方法.

    var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
    settings.TypeNameHandling = TypeNameHandling.Auto;
    
  2. 或者,您可以更改您的 Web API 方法以创建并返回一个 HttpResponseMessageStringContent对象包含您的 JSON 和 mediaType设置为 application/json .这应该可以防止 Web API 尝试重新序列化结果。

    string json = JsonConvert.SerializeObject(monitors, new JsonSerializerSettings 
    {
        TypeNameHandling = TypeNameHandling.Auto,
        Formatting = Formatting.Indented
    }); 
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(json, Encoding.UTF8, "application/json");
    return response;
    

关于c# - 复杂对象的Json.Net反序列化——包含基类作为属性的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36184162/

相关文章:

c# - 前后端同步日期格式

c# - 从 JSON 字符串中获取特定值

json - 反序列化缺少第一列的数据表

asp.net - JSON.NET 读取 JObject 时出错

c# - 可以在 API 上执行功能吗?

c# - 一个动态程序集中的多种类型比多个动态程序集各有一种类型慢得多

c# - ASP.NET Web Api - 使用分块传输编码时,框架不会将 JSON 转换为对象

c# - 列表列表的组合,使每个组合都有唯一的元素

c# - CaSTLe 项目 DynamicProxy 是否大量使用反射?

c# - 如何从具有多对多关系的 C# Web API Visual Studio 2017 RTM 服务(GET)复杂(嵌套)JSON?