I have been attempting to resolve this issue for several hours. I have tried many approaches and read many posts. I can't seem to find a resolution.
I have an object hierarchy whereby I have derived types that contain another derived type. I am using Json.Net's TypeNameHandling setting. I have it set to Auto on both serialization and deserialization.
The resulting JSON is:
"[\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]"
When attempting to deserialize using the following:
string json = response.Content.ReadAsStringAsync().Result;
IEnumerable<MonitorBase> monitors = JsonConvert.DeserializeObject<IEnumerable<MonitorBase>>(json, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
});
I receive the following exception:
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.
The HeartbeatMonitor and DiskSpaceMonitor types derive from MonitorBase and their respective Instructions types derive from MonitorInstructionBase.
I can't help but assume that I am missing something obvious as I can't imagine that this isn't a rather common scenario.