I would like to run some code every time a specific class is being deserilized. (I cannot access//modify the class to add the [OnDeserialized]
attributes)
My first approach was to use a custom jsonconverter and run some code in readjson. Thing is, the custom classes can be complex and working on deserializing all child properties sounds too much (when all gets deserialized properly without the converter).
Is there a way to add custom code whenever a type is deserialized? Or how to use the jsonconverter readjson to create and recursively populate its content (as the deserializer does without converters)?
Also one thing, the type is derived, so i cannot use the Jsonconverter.CanConvert method. (as it triggers on the base type)
This is just some ideas i used in readjson
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load the JSON for the Result into a JObject
JObject jObject = JObject.Load(reader);
// Read the properties which will be used as constructor parameters
//var enemy = Activator.CreateInstance(null, jObject["$type"]);
object t = jObject["$type"];
string[] split = t.ToString().Split(',');
string ass = split[1].Trim();
string typ = split[0];
var allassemblies = AppDomain.CurrentDomain.GetAssemblies();
Assembly a = null;
foreach (Assembly assembly in allassemblies)
{
if (assembly.FullName.StartsWith(ass))
{
a = assembly;
break;
}
}
Type tt = a.GetType(typ);
var instance = Activator.CreateInstance(tt);
//DO I REALLY NEED TO RECURSIVELY WORK THROUGH THE CONTENT (how to populate the instance?)
//SOME CUSTOM CODE dependant on the deserialized type
//before returning change working dir to the auc addons settings directory
AddonUserControl auc = instance as AddonUserControl;
dm_addon dma = AddonManager.FindAddonDataByAUCAssembly(auc);
SystemExtensions.SetRelativeWorkingDirectory("settings//" + dma.Path);
return instance;
}
Please note I cannot modify the type(s) being deserialized.