Consider next code snippet:
static void Main(string[] args)
{
var classes = new Classes()
{
Instances = new A[]{
new B
{
BirthDate = DateTime.Now,
Name = "B1",
SomethingElse = "Test"
},
new C
{
Name = "C1",
SomethingElse1 = "Test2",
SomethingElse2 = "Test3",
}
}
};
var serialized = JsonConvert.SerializeObject(classes);
var deserialized = JsonConvert.DeserializeObject<Classes>(serialized);
}
}
public class Classes
{
public A[] Instances { get; set; }
}
public enum ClassType
{
B = 1,
C = 2
}
public class A
{
public string Name { get; set; }
public virtual ClassType ClassType { get; }
}
public class B : A
{
public string SomethingElse { get; set; }
public DateTime BirthDate { get; set; }
public override ClassType ClassType => ClassType.B;
}
public class C : A
{
public string SomethingElse1 { get; set; }
public string SomethingElse2 { get; set; }
public override ClassType ClassType => ClassType.C;
}
I need to inject my own logic into the process how deserializer handle classes with inheritance. In that case I want to make decision based on ClassType property in JSON. Any ideas/hints how to do it?
BTW. I know that I can use feature of newtonsoft.json TypeNameHandling = TypeNameHandling.All
, however I cannot control serialization process since the data is sent from 3rd party system. The only thing that I have control over is deserialization part.