using System; using System.Linq; using System.Reflection; using Newtonsoft.Json; namespace WorkerService.Process { /// /// Action (void function) JSON converter /// public class ActionConverter : JsonConverter { /// /// Writes the JSON representation of the object /// /// The JsonWriter to write to /// The value to write /// The calling serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is Action action) { writer.WriteValue($"{action.Method.DeclaringType}.{action.Method.Name}"); } } /// Reads the JSON representation of the object. /// The to read from. /// Type of the object. /// The existing value of object being read. /// The calling serializer. /// The object value. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { //Get the method's full path string fullMethodPath = (string)reader.Value; if (string.IsNullOrEmpty(fullMethodPath)) { return null; } //Extract class and method's names string className = fullMethodPath.Substring(0, fullMethodPath.LastIndexOf(".", StringComparison.Ordinal)); string methodName = fullMethodPath.Substring(fullMethodPath.LastIndexOf(".", StringComparison.Ordinal) + 1); //Get the class type Type classType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).FirstOrDefault(t => string.Equals(t.FullName, className, StringComparison.CurrentCultureIgnoreCase)); if (classType == null) { return null; } //Get the function's method info MethodInfo methodInfo = classType.GetMethod(methodName); if (methodInfo == null) { return null; } return (Action)methodInfo.CreateDelegate(typeof(Action)); } /// /// Determines whether this instance can convert the specified object type /// /// Type of the object /// /// Whether or not this instance can convert ot the specified object type /// public override bool CanConvert(Type objectType) { return objectType == typeof(Action); } } }