• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Jil序列化JSON使用Jil序列化JSON提升Asp.netwebapi性能

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 

JSON序列化无疑是Asp.net web api 里面性能提升最重要的一环。

在Asp.net web api 里面我们可以插入自定义的MediaTypeFormatter(媒体格式化器),

说白了就是根据HTTP content-type application/json

来判断采用哪种媒体格式化器

具体实现,记得要引入Jil包


 

  public class JilFormatter : MediaTypeFormatter
        {
        private readonly Options _jilOptions;
        private MethodInfo _method;

        public JilFormatter()
            {
            //要序列化的时间格式
            _jilOptions = new Options(dateFormat: DateTimeFormat.ISO8601);
            //媒体类型
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            //加入 UTF8Encoding 编码
            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
            //加入 UnicodeEncoding 编码
            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));


            }
        //判断是否反序列化类型
        public override bool CanReadType(Type type)
            {
            if (type == null)
                {
                throw new ArgumentNullException("type");
                }
            return true;
            }
        //判断是否序列化类型
        public override bool CanWriteType(Type type)
            {
            if (type == null)
                {
                throw new ArgumentNullException("type");
                }
            return true;
            }

        //  异步反序列化一个指定类型的对象。
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
            {
            return Task.FromResult(DeserializeFromStream(type, readStream));
            }

        private object DeserializeFromStream(Type type, Stream readStream)
            {
            try
                {
                using (var reader = new StreamReader(readStream))
                    {
                    return JSON.Deserialize(reader, type, _jilOptions);
                    }
                }
            catch
                {
                return null;
                }
            }

        //  异步序列化一个指定类型的对象。
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
            {
            var streamWriter = new StreamWriter(writeStream);
            JSON.Serialize(value, streamWriter, _jilOptions);
            streamWriter.Flush();
            return Task.FromResult(writeStream);
            }
        }

 

加入到媒体格式化器集合中

 public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            
                );
GlobalConfiguration.Configuration.Formatters[0] = new JilFormatter(); } }

控制类

  public class HomeController : ApiController
        {
     public static   List<Market> Markets = new List<Market>();

        public HomeController()
            {
          
            }

         static HomeController()
            {
            Markets.Add(new Market { Id = 1, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 2, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 3, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 4, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 5, Name = "1", DateTimeNow = DateTime.Now });
            }
        public IEnumerable<Market> Get()
            {
            return Markets;
            }
        public HttpResponseMessage Post([FromBody]Market value)
            {
            Markets.Add(value);
            return new HttpResponseMessage(HttpStatusCode.OK);
            }

        public HttpResponseMessage Put(int id, [FromBody]Market value)
            {
            var market = Markets.Where(x => x.Id == id).FirstOrDefault();
            if (market == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            market.Name = value.Name;
            return new HttpResponseMessage(HttpStatusCode.OK);
            }

        public HttpResponseMessage Delete(int id)
            {
            var result = Markets.Remove(Markets.Where(x => x.Id == id).FirstOrDefault());
            return result
                ? new HttpResponseMessage(HttpStatusCode.Accepted)
                : new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }

 

我们通过postman访问

我们在post一个实体

 

我们在get一下

 

已经可以看见刚才post的实体了。

源码:http://pan.baidu.com/s/1i3o6KD3

Asp.net Mvc vnext 系列  http://www.cnblogs.com/liek/p/4634294.html

得到你的肯定是我最大的动力!

 
Asp.net vnext

JSON序列化无疑是Asp.net web api 里面性能提升最重要的一环。

在Asp.net web api 里面我们可以插入自定义的MediaTypeFormatter(媒体格式化器),

说白了就是根据HTTP content-type application/json

来判断采用哪种媒体格式化器

具体实现,记得要引入Jil包


 

  public class JilFormatter : MediaTypeFormatter
        {
        private readonly Options _jilOptions;
        private MethodInfo _method;

        public JilFormatter()
            {
            //要序列化的时间格式
            _jilOptions = new Options(dateFormat: DateTimeFormat.ISO8601);
            //媒体类型
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            //加入 UTF8Encoding 编码
            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
            //加入 UnicodeEncoding 编码
            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));


            }
        //判断是否反序列化类型
        public override bool CanReadType(Type type)
            {
            if (type == null)
                {
                throw new ArgumentNullException("type");
                }
            return true;
            }
        //判断是否序列化类型
        public override bool CanWriteType(Type type)
            {
            if (type == null)
                {
                throw new ArgumentNullException("type");
                }
            return true;
            }

        //  异步反序列化一个指定类型的对象。
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
            {
            return Task.FromResult(DeserializeFromStream(type, readStream));
            }

        private object DeserializeFromStream(Type type, Stream readStream)
            {
            try
                {
                using (var reader = new StreamReader(readStream))
                    {
                    return JSON.Deserialize(reader, type, _jilOptions);
                    }
                }
            catch
                {
                return null;
                }
            }

        //  异步序列化一个指定类型的对象。
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
            {
            var streamWriter = new StreamWriter(writeStream);
            JSON.Serialize(value, streamWriter, _jilOptions);
            streamWriter.Flush();
            return Task.FromResult(writeStream);
            }
        }

 

加入到媒体格式化器集合中

 public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            
                );
GlobalConfiguration.Configuration.Formatters[0] = new JilFormatter(); } }

控制类

  public class HomeController : ApiController
        {
     public static   List<Market> Markets = new List<Market>();

        public HomeController()
            {
          
            }

         static HomeController()
            {
            Markets.Add(new Market { Id = 1, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 2, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 3, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 4, Name = "1", DateTimeNow = DateTime.Now });
            Markets.Add(new Market { Id = 5, Name = "1", DateTimeNow = DateTime.Now });
            }
        public IEnumerable<Market> Get()
            {
            return Markets;
            }
        public HttpResponseMessage Post([FromBody]Market value)
            {
            Markets.Add(value);
            return new HttpResponseMessage(HttpStatusCode.OK);
            }

        public HttpResponseMessage Put(int id, [FromBody]Market value)
            {
            var market = Markets.Where(x => x.Id == id).FirstOrDefault();
            if (market == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            market.Name = value.Name;
            return new HttpResponseMessage(HttpStatusCode.OK);
            }

        public HttpResponseMessage Delete(int id)
            {
            var result = Markets.Remove(Markets.Where(x => x.Id == id).FirstOrDefault());
            return result
                ? new HttpResponseMessage(HttpStatusCode.Accepted)
                : new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }

 

我们通过postman访问

我们在post一个实体

 

我们在get一下

 

已经可以看见刚才post的实体了。

源码:http://pan.baidu.com/s/1i3o6KD3

Asp.net Mvc vnext 系列  http://www.cnblogs.com/liek/p/4634294.html

得到你的肯定是我最大的动力!


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap