问题
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?
回答1:
Use JsonConvert.DeserializeObject(string, Type):
var jobj = JsonConvert.DeserializeObject(sJsonText, myType);
Or if you prefer
dynamic jobj = JsonConvert.DeserializeObject(sJsonText, myType);
来源:https://stackoverflow.com/questions/32371532/deserialize-json-text-to-a-specific-object-type-using-the-type-name