When I serialize my Page
object, Json.Net is not adding the $type property to my Controls (which are in an IList
) when it serializes them. I have tried adding the following code to my class constructor and to my WebAPI Startup, but Json.Net is still not adding the $type information to the Control
it serializes.
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
};
For testing purposes, I added the $type
property to the Control myself in the JSON code, and Json.Net was able to deserialize the object correctly, but it is still not serializing correctly. Here's how my classes are setup.
public class Page {
public Guid Id { get; set; }
public Guid CustomerId { get; set; }
public IList<Control> Controls { get; set; }
}
And here is the Control class:
public class Control : ControlBase
{
public override Enums.CsControlType CsControlType { get { return Enums.CsControlType.Base; } }
}
And here is the ControlBase abstract class:
public abstract class ControlBase
{
public Guid Id { get; set; }
public virtual Enums.CsControlType CsControlType { get; }
public Enums.ControlType Type { get; set; }
public string PropertyName { get; set; }
public IList<int> Width { get; set; }
public string FriendlyName { get; set; }
public string Description { get; set; }
}
And here is the OptionsControl which is derived from Control:
public class OptionsControl : Control
{
public override Enums.CsControlType CsControlType { get { return Enums.CsControlType.OptionsControl; } }
public IDictionary<string, string> Options;
}
And this is how the JSON comes out:
"Pages": [
{
"Id": "00000000-0000-0000-0000-000000000000",
"CustomerId": "00000000-0000-0000-0000-000000000000",
"Controls": [
{
"Options": {
"TN": "TN"
},
"CsControlType": 4,
"Id": "00000000-0000-0000-0000-000000000000",
"Type": 4,
"PropertyName": "addresses[0].state",
"Width": [
2,
2,
6
],
"FriendlyName": "State",
"Description": null
}
]
}
]
As you can see, Json.Net did not add the $type
property to the JSON object. The problem is that sometimes I need Json.Net to give me a base Control
object but sometimes I need it to give me an instance of the OptionsControl
object (which inherits from Control
). Why is Json.Net not adding the $type property to my Controls?