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 ...
随机推荐
- c# webbrowser 错误捕获
private void Form1_Load(object sender, EventArgs e) { webBrowser1.Url = new Uri("about:blank&qu ...
- linux包之bash之内置命令ulimit
概述 [root@localhost ~]# rpm -qa|grep bashbash-4.1.2-15.el6_4.x86_64 linux limits.conf 配置 limits.conf ...
- unity htc vive, ugui for vr
http://wacki.me/blog/2016/06/vr-gui-input-module-for-unity-htc-vive/
- wikioi 1202 求和(求n个数的和)
/*============================================================= 1202 求和 题目描述 Description 求n个数的和 输入描述 ...
- pouchdb Conflicts
Conflicts are an unavoidable reality when dealing with distributed systems. And make no mistake: cli ...
- IntelliJ IDEA中配置reportNG
找了好多资料,各种设置都是eclipse上面的.后来发现原来就在Run->Edit Configurations->TestNG->Configuration->Listenn ...
- maven本地仓库
引入某一个站点的jar包 <repositories> <repository> <id>maven.seasar.org</id> <name& ...
- C#分析搜索引擎URL得到搜索关键字,并判断页面停留时间以及来源页面
前台代码: var start; var end; var state; var lasturl = document.referrer; start = new Date($.ajax({ asyn ...
- oc-类目、延展、协议
-----------------------------------------------Category-------------------------------------- 类目 是在原 ...
- Hadoop:使用Mrjob框架编写MapReduce
Mrjob简介 Mrjob是一个编写MapReduce任务的开源Python框架,它实际上对Hadoop Streaming的命令行进行了封装,因此接粗不到Hadoop的数据流命令行,使我们可以更轻松 ...