Manual JSON serialization from DataReader in ASP.NET Web API

In one of my previous blog posts 8 ways to improve ASP.NET Web API performance I talked how we’ve used manual JSON serialization from DataReader to gain some performance benefits.

I haven’t provided any code example, but only link to this excellent blog post from Rick Strahl JSON serialization of a DataReader.

In our production project we’ve used code from Rick Strahl’s blog post to do this.

Instead reading values from DataReader and populating objects and after that reading again values from those objects and producing JSON using some JSON Serializer,  we can directly create a JSON string from DataReader and avoid unnecessary creation of objects.

I’ve received lots of requests to explain this method on my blog.

JsonSerialization

Set up JSON serialization project

As I mention above we’ve used WestWind’s code to do this.

However, this library which is used to perform JSON Serialization is quite large and contains a lot of code that we didn’t need.

So I’ve just extracted the code related to JSON serialization and modified it a little bit to support additional data type and to serialize in CamelCase.

We have also removed some data types we didn’t need.

You can download this modified project library here.

How to use this library

Code for serialization from DataReader to JSON string is very small.

We just need to call the Serialize method and pass the instance of DataReader we want to serialize.

string jsonResult;
var serializer = new WestwindJsonSerializer
{
     DateSerializationMode = JsonDateEncodingModes.Iso
};

using (SqlDataReader reader = cmd.ExecuteReader())
{ 
     jsonResult = serializer.Serialize(reader);
}

 

How to implement this in your ASP.NET Web API controller method

We have implemented code above in our Repository method GetItemsAsJson which is used for retrieving items from database.

The code looks similar to this.

public HttpResponseMessage GetItems([FromUri]ItemQueryParams itemQueryParams)
{

var jsonResult = this.itemRepository.GetItemsAsJson(itemQueryParams);
if (!string.IsNullOrEmpty(jsonResult))
{
     var response = Request.CreateResponse(HttpStatusCode.OK);
     response.Content = new StringContent(jsonResult, Encoding.UTF8, "application/json");
     return response;
}
...
...
}

 

If you like this article don’t forget to subscribe to this blog and make sure you don’t miss new upcoming blog posts.

 

2 Comments on Manual JSON serialization from DataReader in ASP.NET Web API

    • Radenko Zec
      October 20, 2014 at 7:03 pm (10 years ago)

      Hi Vedran. Thanks for comment.

      Yep, Rick is full of great blog posts.

      Reply

Leave a Reply