0

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?

Notaras
  • 611
  • 1
  • 14
  • 44

1 Answers1

1

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

Dan D
  • 2,493
  • 15
  • 23
  • Theres something about `new[]{...}` that doesnt seem to sit well. Even though the json fields map directly to the parameter names, it gives an error saying 'mismatched parameters' or something like that. luckily, there is a way to map these parameter names as per [here](https://stackoverflow.com/questions/13071805/dynamic-invoke-of-a-method-using-named-parameters) – Notaras Aug 10 '17 at 04:58
  • Yeah sorry, I was typing it using implicitly typed arrays. If you specify new object[] that should do the trick. Updated answer – Dan D Aug 10 '17 at 12:00