0

I want to deserialize an object at runtime and cannot figure out how to pass in the type without actually passing in model type.

E.g.

JsonConvert.DeserialzeObject(objectToDeserialize);

I want to be able to do something like this:

Type runtimeType = Type.GetType("namespace_and_class_name");

var result = JsonConvert.DeserializeObject<runtimeType>(objectToDeserialize);

or something like:

var result = JsonConvert.DeserializeObject<Type.GetType(stringOfType)>(objectToDeserialize);
TheAkhemist
  • 219
  • 1
  • 14
  • Think about this, if what you wanted to do did actually work how would you write your next line of code that used `result` if `var` did not exist in the language. – Scott Chamberlain Feb 18 '16 at 15:29

1 Answers1

3

Use this other overload instead:

object result = JsonConvert.DeserializeObject(json, type);

Bear in mind that because the type is not known at compile time, the code cannot be generic anymore. You have to use object instead.

dcastro
  • 66,540
  • 21
  • 145
  • 155