简体   繁体   中英

How do I deserialize json into PropertyType?

I'm trying to create a new instance of a property by deserializing a json string. The call to JsonConvert.DeserializeObject<T>(string) works when I explicitly state the type of T :

var foo = JsonConvert.DeserializeObject<Resource>(propertyValue.ToString());

But I'd like to pass it PropertyInfo.PropertyType :

var foo = JsonConvert.DeserializeObject<prop.PropertyType>(propertyValue.ToString());

I get "type or namespace 'prop' could not be found." This doesn't make sense to me, I thought that PropertyType is a 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. This solves your question but you are still left with a reference to a type that is not of your prop.PropertyType .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM