JavaScriptSerializer non-generic Deserialize method
July 10th, 2008I was messing around with the ASP.NET MVC Preview 3 the other evening and ran into a “problem” with the JavaScriptSerializer. The class provides two methods for deserializing an object from JSON data:
public T Deserialize<T>(string data);
public object DeserializeObject(string data);
A notable omission from the API is a non-generic method for deserializing to a specific type, i.e.:
public object Deserialize(Type type, string data);
This method would be useful when dynamically deserializing objects, using reflection for instance.
Digging around with Reflector I found that the generic method just delegates to an internal helper, passing the generic parameter T as typeof(T). It would be a simple matter then to provide the necessary overload that accepts the Type directly.
Hopefully the ASP.NET team will add the missing overload, but in the meantime I decided to "cheat" with the following extension method:
public static class JavaScriptSerializerExtensions
{
public static object Deserialize(this JavaScriptSerializer serializer,
Type type,
string data)
{
Type serializerType = typeof(JavaScriptSerializer);
object[] args = new object[]
{
serializer,
data,
type,
serializer.RecursionLimit,
};
return serializerType.InvokeMember(
"Deserialize",
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.InvokeMethod,
Type.DefaultBinder,
null,
args);
}
}
December 19th, 2008 at 5:41 am
Thankyou! That omission was causing me considerable pain…