user1032657
user1032657

Reputation: 2471

convert System.Type to a T Parameter

I have the System.Type of an object, and I want to use it as a parameter to a generic function: JsonConvert.DeserializeObject<T>()

Of course JsonConvert.DesierializeObject<theType>() does not work.. I seem to need the name of the class but I am not sure how to get it from the type.

Is there a way to convert the type back into a T so I can call the function?

Upvotes: 3

Views: 1082

Answers (2)

Charlie
Charlie

Reputation: 1332

Are you using json.net? JsonConvert has another method

 public static object DeserializeObject(string value, Type type);

you can use this one,like

var result = JsonConvert.DeserializeObject("{ some json }", theType);

Upvotes: 3

Łukasz W.
Łukasz W.

Reputation: 9755

I guess that DeserializeObject is a static method? Try to use reflection:

var methodInfo = typeof(JsonConverter).GetMethod("DeserializeObject", System.Reflection.BindingFlags.Static | BindingFlags.Public);
var genericArguments = new Type[] { theType };
var genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments );
var result = genericMethodInfo.Invoke(null, null);

And if DeserializeObject tooks some parameters then pass them in the second parameter of Invoke method in the last line...

Upvotes: 7

Related Questions