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?
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
Use JsonConvert.DeserializeObject(string, Type)
:
var jobj = JsonConvert.DeserializeObject(sJsonText, myType);
Or if you prefer
dynamic jobj = JsonConvert.DeserializeObject(sJsonText, myType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With