Search code examples
jsonreflectionsystem.reflectionmethodinfo

C# MethodInfo Invoke() with JSON args


the Invoke() function on a MethodInfo object accepts parameters as an object[]. I want to be able to send a JSON encoded string instead. Is there any way to do this?

The code which i am basing mine of comes from this MSDN page

....
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);

//args in this case is an object[]. any way to pass a string?
return mi.Invoke(wsvcClass, args);

I am aware that Newtonsoft provides a way to deserialize strings but can it do so into an object[]? or is there another way to do this?


Solution

  • The method signature you are looking at takes an Object[] representing all parameters in your method. For example:

    public void DoStuff(string x, string y, int b);
    

    Could be called like this:

    methodInfo.Invoke(wscvClass, new object[] { "x", "y string", 500 });
    

    So in your case you should be able to call Invoke using:

    string jsonEncodedString = "{ }"; // whatever you need to do to get this value
    mi.Invoke(wsvcClass, new object[] { jsonEncodedString });
    

    MethodInfo MSDN Link