0

I have a JSON string that is received via a WebSocket and I have to deserialize it and then call a method on it. Let's suppose I also know it's type, but only in run-time as well.

var value = GetJson();
var type = Assembly.LoadWithPartialName("xxx").GetType("yyy");
var req = JsonConvert.DeserializeObject(value, type);

req.DoAction();

As a result I get an error that says 'object' does not contain a definition for 'DoAction' and no accessible extension method 'DoAction'

misticos
  • 718
  • 5
  • 22
Toon
  • 13
  • 3
  • `DeserializeObject()` returns `Object`. You can cast it to the type. Or maybe use `dynamic`. – 001 Feb 21 '20 at 13:48

1 Answers1

1

You only know the type at run-time. So, you should use dynamic in such case. Also you can change it's type.

Type type; // We know these both values
string json;

dynamic result = JsonConvert.DeserializeObject(json, type);
dynamic obj = Convert.ChangeType(result, paramType);

obj.DoAction();

The code above should make it work. Make sure it actually contains such method or inherits a specific class and etc to prevent any possible errors.

misticos
  • 718
  • 5
  • 22