I have a simple use case where I want to deserialize a JSON that is basically an array of items, items are not identical but they all share a base class.
UPDATE: my technical limitations:
- I receive the JSON from a webhook and can't alter the serialization code or inject any tokens in the source JSON
- The
Type
property is the only information to do the correspondence between the derived class that I want to deserialize to - need strongly typed instances and not
dynamic
ones - The classes are in an assembly and I can't add any Json Annotations
Here is the code:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var json = @" [{""Type"":0},{""Name"":""Derived"",""Type"":1}]";
var deserializedInstances = JsonConvert.DeserializeObject<List<BaseClass>>(json);
foreach(var e in deserializedInstances) {
if(e is BaseClass baseClass)
{
Console.WriteLine("Base Class , Type = {0}", baseClass.Type);
}else if(e is DerviedClass derivedClass)
{
Console.WriteLine("Derived Class , Type = {0}, Name = {1}", derivedClass.Type, derivedClass.Name);
}
}
// Output
// Base Class , Type = 0
// Base Class , Type = 0
}
public class BaseClass
{
public virtual int Type =>0;
}
public class DerviedClass: BaseClass
{
public string Name {get; set;}
public override int Type =>1;
}
}
so this code will produce this output:
// Base Class , Type = 0
// Base Class , Type = 0
but in my case, I want to have the instance of the derived class.
// Base Class , Type = 0
// Base Class , Type = 1, Name = "Derived"
What is the best way to achieve this in terms of performance?