Good Afternoon Everyone, I am trying to dynamically invoke a function by passing its appropriate parameters. Let's say the function looks like this:
public string CreatePerson(Person p)
Object p is received as Json and I want to deserialize it into the appropriate runtime Type depending on the parameter Type so that I can pass it into the Newtonsoft.Json library function JsonConvert.DeserializeObject (jsonReceived).
Below is my code:
m = this.GetType().GetMethod(method);
List<object> a = new List<object>();
foreach (var param in m.GetParameters())
{
//have to convert args parameter to appropriate function input
a.Add(ProcessProperty(param.Name, param.ParameterType, args));
}
object invokeResult = null;
invokeResult = m.Invoke(this, a.ToArray());
private object ProcessProperty(string propertyName, Type propertyType, string jsonStringObject)
{
if (propertyType.IsClass && !propertyType.Equals(typeof(String)))
{
var argumentObject = Activator.CreateInstance(propertyType);
argumentObject = JsonConvert.DeserializeObject<propertyType>(jsonStringObject);
return argumentObject;
}
}
I get the following error :
The type or namespace name 'propertyType' could not be found (are you missing a using directive or an assembly reference?)
Where am I approaching this wrong? How can I get the parameter Type dynamically during runtime so it can handle types other than Person and be able to pass it to DeserializeObject?
JsonConvert.DeserializeObject(jsonStringObject, propertyType)