Jil序列化JSON

使用Jil序列化JSON提升Asp.net web api 性能

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

时间: 2024-10-05 19:01:39

Jil序列化JSON的相关文章

使用Jil序列化JSON提升Asp.net web api 性能

JSON序列化无疑是Asp.net web api 里面性能提升最重要的一环. 在Asp.net web api 里面我们可以插入自定义的MediaTypeFormatter(媒体格式化器), 说白了就是根据HTTP content-type application/json 来判断采用哪种媒体格式化器 具体实现,记得要引入Jil包 public class JilFormatter : MediaTypeFormatter { private readonly Options _jilOpti

mvc 使用Newtonsoft.Json进行序列化json数据

mvc 使用Newtonsoft.Json进行序列化json数据 JsonResult  使用js 序列号化,先集成扩展.使用newtonsoft http://blog.csdn.net/zhangyuanwei88/article/details/38556689

Entity中Lazy Load的属性序列化JSON时报错

The server encountered an internal error that prevented it from fulfilling this request.org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: com.party.dinner.entit

使用 ServiceStack.Text 序列化 json的实现代码

相信做 .net 开发的朋友经常会遇到 json 序列化这样的需要,今天发篇文章总结下自己使用ServiceStack.Text 来序列化 json.它的速度比 Newtonsoft.Json 快很多,在测试时发现比 fastJson 还快些. 首先,我们有下边两个类,一个是职员(Staff)类,一个是联系方式(Contact)类: public class Staff { public long ID { get; set; } public string Name { get; set; }

jquery将表单序列化json对象

$.fn.serializeObject = function () { var obj = {}; var count = 0; $.each(this.serializeArray(), function (i, o) { var n = o.name, v = o.value; count++; obj[n] = obj[n] === undefined ? v : $.isArray(obj[n]) ? obj[n].concat(v) : [obj[n], v]; }); //obj.

Xml 序列化 Json 反序列化

#region 全局变量 /// <summary> /// 全局变量 /// </summary> XmlDocument XmlDoc = new XmlDocument(); #endregion #region 加载 public ParseJosn() { InitializeComponent(); ParseJson(XmlPaerseJson()); } #endregion #region Json 转换Model /// <summary> ///

java list序列化json 对象、json数组

list<T> 序列化   json对象   ----------- JSONObject -------JSONObject.toJSONString(str);  解析:JSONObject.parseArray(str,T.class); list<T> 序列化   json数组   ----------- JSONArray -------JSONArray.toJSONString(str);    解析; JSONArray.parseArray

C#序列化JSON

public static string ConvertToJsonString<T>(T instance) {             using (MemoryStream stream = new MemoryStream())     { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); serializer.WriteObject(stream, instance);

C# 把对象序列化 JSON 字符串 和把JSON字符串还原为对象

/// <summary> /// 把对象序列化 JSON 字符串 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="obj">对象实体</param> /// <returns>JSON字符串</returns> public static string GetJson<