2

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.

3
  • 1
    Generics don't work like that. Commented Mar 20, 2014 at 19:28
  • @SLaks Ok, is there an alternative I can try? A different approach? Commented Mar 20, 2014 at 19:31
  • Here PropertyType is a property that holds a Type; it is not a type itself. Generics must be able to be resolved at compile time. Commented Mar 20, 2014 at 20:38

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.