几个小时以来,我一直在尝试解决这个问题。我尝试了很多方法并阅读了很多帖子。我似乎找不到解决办法。
我有一个对象层次结构,其中我有包含另一个派生类型的派生类型。我正在使用 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.
HeartbeatMonitor
和 DiskSpaceMonitor
类型派生自 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 设置,并且您正在寻找一种避免双重序列化的方法。
你基本上有两个选择:
添加
TypeNameHandling
设置为 Web API 的全局序列化设置,并从您的方法中删除手动序列化代码。为此,请在Application_Start()
中添加以下内容global.asax
中的方法.var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings; settings.TypeNameHandling = TypeNameHandling.Auto;
或者,您可以更改您的 Web API 方法以创建并返回一个
HttpResponseMessage
用StringContent
对象包含您的 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/