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

泄露秘密 提交于 2020-01-24 08:52:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!