Deserialize JSON text to a specific object type using the Type name

15,622

Use JsonConvert.DeserializeObject(string, Type):

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

Or if you prefer

dynamic jobj = JsonConvert.DeserializeObject(sJsonText, myType);
Share:
15,622
Heba Gomaah
Author by

Heba Gomaah

Updated on June 20, 2022

Comments

  • Heba Gomaah
    Heba Gomaah almost 2 years

    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?