Replace JSON.NET with ServiceStack.Text in ASP.NET Web API
Because ServiceStack.Text performs much better
I recently stumbled across a comparison of JSON serialization libraries. which shows that ServiceStack.Text by far outperforms any of the competitors. Indeed, the folks down at ServiceStack have been building a lot of great stuff for the past few (4?) years to facilitate their framework.
ServiceStack.Text is available on Nuget and can be used outside of ServiceStack, within any .NET project, so why not use it with Web API, replacing the default serializer, JSON.NET?
Let’s do that.
Creating a ServiceStack.Text MediaTypeFormatter
Typically, whenever you want to introduce a new serialziation mechanism to ASP.NET Web API, you’d create a new MediaTypeFormatter. This case is no different. Let’s grab ServiceStack.Text from Nuget:
Install-Package ServiceStack.Text
Once you have it refrenced in your solution, the formatter is pretty straight forward:
public class ServiceStackTextFormatter : MediaTypeFormatter
{
public ServiceStackTextFormatter()
{
JsConfig.DateHandler = JsonDateHandler.ISO8601;
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
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)
{
var task = Task<object>.Factory.StartNew(() => JsonSerializer.DeserializeFromStream(type, readStream));
return task;
} public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
{
var task = Task.Factory.StartNew(() => JsonSerializer.SerializeToStream(value, type, writeStream));
return task;
}
}
We tell the formatter a few things:
– we will support application/json media type
– we support UtF-8 and Unicode encoding
– Read and Write is available for all types of objects
– we tell ServiceStack to handle dates as ISO8601, to avoid JSON dates with Unix Epoch milliseconds (read more here)
– in the read/write methods we simply asynchronously call the respective methods of the ServiceStack.Text.JsonSerializer
Replacing JSON.NET
Now, in order to wire this up, we need to remove the default JSON formatter (JSON.NET) and inject our new formatter into the GlobalConfiguration.Formatters collection.
public static void Register(HttpConfiguration config)
{
config.Formatters.RemoveAt();
config.Formatters.Insert(, new ServiceStackTextFormatter()); //continue with config
}
And that’s it!
From now your ASP.NET Web API application will be using ServiceStack.Text, a serializer which benchmarks show is almost 2x faster than JSON.NET. In all fairness, that’s one of the micro optimizations, but still, if you can improve something, why not do that?
Replace JSON.NET with ServiceStack.Text in ASP.NET Web API的更多相关文章
- ASP.NET WEB API 返回JSON 出现2个双引号问题
前言 在使用ASP.NET WEB API时,我想在某个方法返回JSON格式的数据,于是首先想到的就是手动构建JSON字符串,如:"{\"result\" ...
- ASP.NET Web API中的JSON和XML序列化
ASP.NET Web API中的JSON和XML序列化 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok ...
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- 让ASP.NET Web API支持POST纯文本格式(text/plain)的数据
今天在web api中遇到了这样一个问题,虽然api的参数类型是string,但只能接收post body中json格式的string,不能接收原始string. web api是这样定义的: pub ...
- 让ASP.NET Web API支持text/plain内容协商
ASP.NET Web API的内容协商(Content Negotiation)机制的理想情况是这样的:客户端在请求头的Accept字段中指定什么样的MIME类型,Web API服务端就返回对应的M ...
- ASP.NET Web API 如何通过程序控制返回xml还是json
雖然 ASP.NET Web API 內建支援 JSON 與 XML 兩種輸出格式,並依據瀏覽器端送出的 Accept 標頭自動決定回應的內容格式,不過有時候我們的確也需要讓程式來控制要回應哪種格式, ...
- [转] JSON Web Token in ASP.NET Web API 2 using Owin
本文转自:http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/ ...
- JSON Web Token in ASP.NET Web API 2 using Owin
In the previous post Decouple OWIN Authorization Server from Resource Server we saw how we can separ ...
- On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API
Ints are easy. Strings are mostly easy. Dates? A nightmare. They always will be. There's different c ...
随机推荐
- SDWebImage使用详解
这个类库提供一个UIImageView类别以支持加载来自网络的远程图片.具有缓存管理.异步下载.同一个URL下载次数控制和优化等特征.使用示范的代码:UITableView使用UIImageView+ ...
- 浅析Struts1和Struts2的Action线程安全问题 转
浅析Struts1和Struts2的Action线程安全问题 转 http://blog.csdn.net/virgoboy2004/article/details/5876133 [问题描述]最近 ...
- 反向代理代理百度、google
<VirtualHost _default_:443> # ServerAdmin mail@localhost # DocumentRoot "/var/www/html&qu ...
- Android 不同文件名介绍
Android 不同文件名介绍
- 【linux】find命令详解
find命令格式:find [搜索范围][匹配条件] -name 参数:按照名字查找 [root@andon ~]# find /root -name test ###精确查找 /root/test ...
- Discuz!NT 3.9.913 Beta DIY过程
前提: 论坛的源码版本为dnt_3.9.913_sqlserver_beta.zip,以下例子都以这个版本为原型修改 dnt_3.9.913数据字典:下载 目前(2013年10月21日)官网的asp. ...
- 不包含适合于入口点的静态"Main"方法
学习新建项目.此问题做为笔记. 错误 1 程序“admin.exe”不包含适合于入口点的静态“Main”方法 原因:原来创建项目的时候,用的是“空项目”,我以为这样就会生成类库,实际上,一开始准备运行 ...
- mvc checked=\"checked\"
<input id="IsDiscount" type="checkbox" @(Model != null && Model.IsDis ...
- Spring实战4:面向切面编程
主要内容 面向切面编程的基本知识 为POJO创建切面 使用@AspectJ注解 为AspectJ的aspects注入依赖关系 在南方没有暖气的冬天,太冷了,非常想念北方有暖气的冬天.为了取暖,很多朋友 ...
- Lvs+Keepalived+Squid+Nginx负载均衡
前言* 随着互联网IT行业的发展,越来越多的企业开始使用开源软件搭建自己的web架构,主流的LVS也得到了广泛的应用,在保证高可用的同时,用户对网站的体验速度也有了很高的要求,这时候需要我们在我们的架 ...