• 使用JSON.Net(Newtonsoft.Json)作为ASP.Net MVC的json序列化和反序列化工具


    ASP.Net MVC默认的JSON序列化使用的是微软自己的JavaScriptSerializer。性能低不说,最让人受不了的是Dictionary<,>和Hashtable类型居然对应的json是[{"Key":"a","Value":1}]而不是{"a":1}。真是奇葩到家了,跟前端根本没法集成!

    决定还是用JSON.Net来做吧!查了各种资料,网上的要么代码太复杂,要么没法完全实现。又在ILSpy分析了MVC源码,然后调试了半天,终于有了初步的解决办法:

    1、反序列化,首先建立下面的类:

    原理基本上就是替换系统自带的ValueProviderFactory和DefaultModelBinder,然后改用自己的类来调用JSON.Net实现。

    public class JsonNetValueProviderFactory : ValueProviderFactory
        {
            public override IValueProvider GetValueProvider(ControllerContext ctlContext)
            {
                //if (!controllerContext.HttpContext.Request.ContentType.
                //    StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
                //{
                //    return null;
                //}
    
                var reader = new StreamReader(ctlContext.HttpContext.Request.InputStream);
                reader.BaseStream.Position = 0;
                var json = reader.ReadToEnd()?.TrimStart(' ', '
    ', '
    ', '	');
                if (string.IsNullOrEmpty(json))
                    return null;
    
                var jtoken = json.StartsWith("[")
                    ? JArray.Parse(json) as JContainer
                    : JObject.Parse(json) as JContainer;
                return new JsonNetValueProvider(jtoken);
            }
        }
    
        public class JsonNetValueProvider : IValueProvider
        {
            private JContainer _jValue;
    
            public JsonNetValueProvider(JContainer jval)
            {
                _jValue = jval;
            }
    
            public bool ContainsPrefix(string prefix)
            {
                return true;
            }
    
            public ValueProviderResult GetValue(string key)
            {
                var jtoken = _jValue.SelectToken(key);
                if (jtoken == null)
                {
                    jtoken = _jValue;
                }
                return new JsonNetValueProviderResult(jtoken, key, null);
            }
        }
    
        public class JsonNetValueProviderResult : ValueProviderResult
        {
            private JToken _jtoken;
            public JsonNetValueProviderResult(JToken valueRaw, string key, CultureInfo info)
            {
                _jtoken = valueRaw;
            }
            [System.Diagnostics.DebuggerHidden]
            public override object ConvertTo(Type type, CultureInfo culture)
            {
                return _jtoken?.ToObject(type);
            }
        }
    
        public class JsonNetModelBinder : DefaultModelBinder
        {
            [System.Diagnostics.DebuggerHidden]
            public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                var provider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (provider != null)
                {
                    try
                    {
                        return provider.ConvertTo(bindingContext.ModelType);
                    }
                    catch { }
                }
                return base.BindModel(controllerContext, bindingContext);
            }
        }

    2、然后再Application_Start或者Router初始化时调用下面代码:

                //重置Json序列化方式,改用JSON.Net
                ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.
                    OfType<JsonValueProviderFactory>().FirstOrDefault());
                ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory());
    
                //重置系统的Binder,使Dictionary可以正常json
                ModelBinders.Binders.DefaultBinder = new JsonNetModelBinder();

    3、序列化的过程比较简单,建立一个JsonNetResult类,然后mvc方法返回这个类型就可以了。

     public class JsonNetResult : JsonResult
        {
            public JsonSerializerSettings Settings { get; private set; }
            public override void ExecuteResult(ControllerContext context)
            {
                //if (context == null)
                //    throw new ArgumentNullException("context");
                //if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                //    throw new InvalidOperationException("JSON GET is not allowed");
    
                HttpResponseBase response = context.HttpContext.Response;
                response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
    
                if (this.ContentEncoding != null)
                    response.ContentEncoding = this.ContentEncoding;
                if (this.Data == null)
                    return;
    
                var scriptSerializer = JsonSerializer.Create(this.Settings);
    
                using (var sw = new StringWriter())
                {
                    scriptSerializer.Serialize(sw, this.Data);
                    response.Write(sw.ToString());
                }
            }
        }
  • 相关阅读:
    C++ calculate the time cost in 100 nanoseconds precision
    C++ append file via ofstream
    WCF Server Error in '/' Application.
    Webclient "The operation has timed out" and override webclient with customized timeout
    WPF implement SelectedCommand in MVVM via Interaction.Triggers
    将EDGE浏览器首页中的hao123删除的方法--干净的界面
    PHP 获取当前时间的下一个整点时间
    微信小程序添加空格
    为什么upload下的图片不存在,会报模块不存在的错误
    lnmp环境搭建
  • 原文地址:https://www.cnblogs.com/hz-blog/p/ASP_Net_MVC_JSON_Dictionary_.html
Copyright © 2020-2023  润新知