Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 264
Heba Gomaah Avatar asked Sep 03 '15 09:09

Heba Gomaah


People also ask

How do I deserialize an object in JSON?

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.

What is JsonProperty annotation C#?

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.

What is the difference between serialize and deserialize JSON?

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).


1 Answers

Use JsonConvert.DeserializeObject(string, Type):

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

Or if you prefer

dynamic jobj = JsonConvert.DeserializeObject(sJsonText, myType);
like image 100
dbc Avatar answered Sep 18 '22 15:09

dbc