使用Type名称将JSON文本反序列化为特定的对象类型 [英] Deserialize JSON text to a specific object type using the Type name
本文介绍了使用Type名称将JSON文本反序列化为特定的对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我曾经使用下面的代码将JSON文本反序列化为强类型对象
I used to deserialize JSON text to a strongly type object using the code below
Trainer myTrainer = JsonConvert.DeserializeObject<Trainer>(sJsonText);
现在我需要将反序列化JSON文本转换为仅知道类型名称的特定类型.
Now I need to convert deserialize JSON text to a specific type knowing only the name of the type.
我试图使用Reflection从名称中获取Type,然后将其与JsonConvert一起使用,如下所示:
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?
推荐答案
使用 JsonConvert.DeserializeObject(string, Type)
:
var jobj = JsonConvert.DeserializeObject(sJsonText, myType);
或者,如果您愿意
dynamic jobj = JsonConvert.DeserializeObject(sJsonText, myType);
这篇关于使用Type名称将JSON文本反序列化为特定的对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文