8

I used to deserialize JSON text to a strongly type object using the code below

Trainer myTrainer = JsonConvert.DeserializeObject<Trainer>(sJsonText);

Now I need to convert deserialize JSON text to a specific type knowing only the name of the type.

I tried to use Reflection to get the Type from its name then use this type with JsonConvert as shown below:

Type myType = Type.GetType("Trainer");
var jobj = JsonConvert.DeserializeObject<myType >(sJsonText);

but unfortunately, the error below shown up:

CS0118  'myType' is a variable but is used like a type

Is there a way that I can make reference to a class using a string?

Heba Gomaah
  • 1,145
  • 4
  • 11
  • 16

1 Answers1

22

Use JsonConvert.DeserializeObject(string, Type):

var jobj = JsonConvert.DeserializeObject(sJsonText, myType);

Or if you prefer

dynamic jobj = JsonConvert.DeserializeObject(sJsonText, myType);
dbc
  • 104,963
  • 20
  • 228
  • 340
  • Thanks a lot @dbc it works like a charm. but I still need to know a way to make reference to a class using a string as I want to pass myType to [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) – Heba Gomaah Sep 03 '15 at 09:33
  • 1
    @HebaGomaah - use `MakeGenericMethod`. See [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method). – dbc Sep 03 '15 at 09:38
  • thanks a lot that is exactly what I was looking for. – Heba Gomaah Sep 03 '15 at 09:57