码迷,mamicode.com
首页 > Web开发 > 详细

Jil序列化JSON

时间:2015-10-18 00:54:59      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:

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

Jil序列化JSON

标签:

原文地址:http://www.cnblogs.com/Leo_wl/p/4888621.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!