0

I have the following classes (names and property names have been changed):

[KnownType(typeof(Module))]
[DataContract]
public class BaseModule
{
    [DataMember]
    public int Id { get; set; }
}

[DataContract]
public class Module : BaseModule
{
    [DataMember]
    public string Name { get; set; }
}

[DataContract]
public class ModuleContainer
{
    [DataMember]
    public ModuleBase mod { get; set; }
}

So, when using:

var json = @"{\"mod\":{
    \"Name\":\"The Name\",
    \"Id\":10
}}";

var result = JsonConvert.DeserializeObject<ModuleContainer>(json);

The resulting object's "mod" member can't be successfully converted to type Module, and serializing the object again yields no "Name" member. It seems like Json.Net is unable to recognize the inherited type (Module) and instead gives me a "ModuleBase" object.

I have a fairly large number of inherited classes (all different, and all covered by KnownType on ModuleBase). Is there a way in which I can convince JsonConvert to grab the appropriate type?

Let me know if you need more information, or that was confusing.

TheMonarch
  • 577
  • 1
  • 5
  • 19
  • @dbc, that only works if the JSON I'm receiving is from an appropriate source (ie: someone using Json.NET); is there any way to have the serializer recognize the correct type without extra type information in the JSON? – TheMonarch Oct 11 '16 at 23:41
  • As stated [here](https://github.com/JamesNK/Newtonsoft.Json/issues/36), Json.NET does not support `__type` type hints in the style of `DataContractJsonSerializer`. Instead, you can create a custom converter along the lines of [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/questions/19307752) to select the correct type. – dbc Oct 11 '16 at 23:46

0 Answers0