Ever wish JavaScriptSerializer had a non-generic Deserialize method (like DataContractJSONSerializer)?

Well, Rex informed me of the handy MethodInfo.MakeGenericMethod which creates a constructed generic method, allowing us to avoid having to declare the generic types at design time.  So, now we can bolt on a Deserialize method (note, we cache the constructed generic methods) (formatted to appease wordpress)

public static class JavaScriptSerializerExtensions
    {
        private static object _lock = new object();
        private static IDictionary<Type, MethodInfo> _deserializers
               = new Dictionary<Type, MethodInfo>();

        private static MethodInfo GetDeserializeMethod(Type type)
        {
            lock (_lock)
            {
                if (_deserializers.ContainsKey(type)==false)
                {
                    var mi = typeof(JavaScriptSerializer)
                        .GetMethod("Deserialize");
                    _deserializers[type] = mi.MakeGenericMethod(type);
                }
            }
            return _deserializers[type];
        }

        public static object Deserialize(
               this JavaScriptSerializer serializer, Type type, string json)
        {
            return GetDeserializeMethod(type).Invoke(
                serializer, new object[] { json });
        }
    }

Leave a comment