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?
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...
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);
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.