[英]How do I deserialize json into PropertyType?
I'm trying to create a new instance of a property by deserializing a json
string. 我正在尝试通过反序列化
json
字符串来创建属性的新实例。 The call to JsonConvert.DeserializeObject<T>(string)
works when I explicitly state the type of T
: 当我明确声明
T
的类型时,对JsonConvert.DeserializeObject<T>(string)
的调用有效:
var foo = JsonConvert.DeserializeObject<Resource>(propertyValue.ToString());
But I'd like to pass it PropertyInfo.PropertyType
: 但我想将其传递给
PropertyInfo.PropertyType
:
var foo = JsonConvert.DeserializeObject<prop.PropertyType>(propertyValue.ToString());
I get "type or namespace 'prop' could not be found." 我得到“找不到类型或名称空间'prop'。” This doesn't make sense to me, I thought that
PropertyType
is a Type
. 这对我来说没有意义,我认为
PropertyType
是Type
。
Take the overload that does accept a type parameter 接受确实接受类型参数的重载
var foo = JsonConvert.DeserializeObject(
propertyValue.ToString(),
prop.PropertyType);
foo will be of type object
in this case. 在这种情况下,foo将为
object
类型。 This solves your question but you are still left with a reference to a type that is not of your prop.PropertyType
. 这解决了您的问题,但是您仍然可以得到对不是
prop.PropertyType
的类型的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.