My use case is this: There are a number of implementations of an interface, ICommand, that are JSON-serialized and sent to another system where they are deserialized and used. Part of the interface spec is a string property with the name of the specific type, since a type is needed for deserialization. Reading the type name from the JSON string and switching based on that is simple and it works, but it's also ugly and the switch needs to be updated every time a new implementation is added or a type name is changed for any reason:
Match match = Regex.Match(json, "\"TypeName\":\".*?\"");
if (match.Success)
{
// Add cases here as new command types are defined
switch (match.Value)
{
case "\"TypeName\":\"TypeNumberOne\"":
return JsonConvert.DeserializeObject<TypeNumberOne>(json);
default:
break;
}
}
What I'm hoping to be able to do is generalize the deserialization in some way. What I'm trying right now is reading the type name out of the JSON and using Type.GetType to get the type, which I'd like in some way to pass to JsonConvert.DeserializeObject<T>. I can get the type just fine, but I can't figure out how to pass it as the T. This
return JsonConvert.DeserializeObject<Type.GetType(string.Format("namespace.{0}", typeName))> (json);
and this
return JsonConvert.DeserializeObject<Type.GetType(string.Format("namespace.{0}", typeName)).MakeGenericType()> (json);
won't even compile; Intellisense says Operator '<' cannot be applied to operands of type 'method group' and 'Type' - evidently it's not seeing the Type-valued expression as a usable T.
Assigning the result of the expression to a variable:
Type commandType = Type.GetType(string.Format("VITL.Library.Commands.{0}", typeName));
return JsonConvert.DeserializeObject<commandType> (json);
results in 'commandType' is a variable but is used like a type.
Is there a way to derive a type at runtime such that it can be used in invoking a generic function?