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 ...
随机推荐
- openjudge-回文串判断【递归】
回文串判断 总时间限制: 1000ms 内存限制: 65536kB 描述 任意给定一个非空的字符串,判断其是否是回文串.回文串是指正向看和反向看均相等的串,如AbcDcbA和cDDc.如果是回文串,则 ...
- 【转】Win7注册表的使用(更新中)
一.注册表的存储结构和数据类型 1.基本概念: Windows 7的注册表主要由“键”和“键值”构成,称HKEY为根键(RootKey),SubKey为子键. 键(Key):“位于左侧窗格如同文件夹图 ...
- python input() 与 raw_input()
使用input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的 当输入为纯数字时: input返回的是数值类型,如int,floatraw_inpo ...
- 导入安卓项目的时候,发生错误:Cause: peer not authenticated
导入安卓项目时出现Cause: peer not authenticated. 在网上搜了解决方案,都没有凑效.后来干脆插上手机直接debug安装,竟然成功了,成功了,成功了!!!! 然后再次buil ...
- Python教程:[69]strip()函数详解
strip()用于裁剪字符串首尾的某些字符,是一个用处非常多的函数,今天我们来通过例子来探讨一下它的基本用法: 假如有一个这样的字符串 strip()不带任何参数,可以删除首位的空格 但是strip( ...
- 将war文件解压到指定目录
问:如何将.war文件解压到指定目录? 答:jar命令没有这样的选项. eg:将abc.war解压到当前文件夹? 答:进入目标文件即abc.war文件所在的文件夹,按住shift键并在该文件夹空白处点 ...
- MySql之on duplicate key update详解
在我们的日常开发中,你是否遇到过这种情景:查看某条记录是否存在,不存在的话创建一条新记录,存在的话更新某些字段.你的处理方式是不是就是按照下面这样? $result = mysql_query('se ...
- R(五): R常用函数
工作笔记记录,会持续更新.... 目录: apply tapply lapply sapply merge substr.substring.strsplit.unlist.paste.paste0. ...
- Eclipse给方法分配足够的内存
junit测试 VM parameters -Xmx1024M -XX:PermSize=128m -XX:MaxPermSize=256m
- js 删除DropDownList的选项
function del_DropDownList_Option() { var ddlXZ= document.getElementById("name&quo ...