Replace JSON.NET with ServiceStack.Text in ASP.NET Web API
2014-09-10 10:02
701 查看
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:Shell
Install-Package ServiceStack.Text
Once you have it refrenced in your solution, the formatter is pretty straight forward:
C#
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.C#
public static void Register(HttpConfiguration config) { config.Formatters.RemoveAt(0); config.Formatters.Insert(0, 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?
Be Sociable, Share!
相关文章推荐
- Replace JSON.NET with Jil JSON serializer in ASP.NET Web API
- [转]Getting started with ASP.NET Web API OData in 3 simple steps
- Manual JSON serialization from DataReader in ASP.NET Web API
- Send and Receive JSON objects to Web Service Methods using jQuery AJAX in ASP.Net
- How do I get ASP.NET Web API to return JSON instead of XML using Chrome
- Virus Scanner induced bug with ASP.NET webservice application
- Creating a Clean, Minimal-Footprint ASP.NET WebAPI Project with VS 2012 and ASP.NET MVC 4
- How to: Configure WCF Service to Interoperate with ASP.NET Web Service Clients
- The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the ser
- Creating a REST service using ASP.NET Web API
- Tracing in ASP.NET Web API
- Working with Web Resources in ASP.NET 2.0
- 转:Working with HttpWebRequest and HttpWebResponse in ASP.NET
- Exception Handling in ASP.NET Web API
- 痴情意外:ASP.NET WebAPI RC 竟然不支持最常用的json传参
- Generate Kindle (MOBI) ebooks with your ASP.NET Web API
- asp.net :使用jquery 的ajax +WebService+json 实现无刷新去后台值
- [ASP.NET AJAX]Important notes when we create web service methods for some extenders in AjaxControlToolkit package
- asp.net :使用jquery 的ajax +WebService+json 实现无刷新去后台值
- Routing in ASP.NET Web API