The S#arp framework: adding support to JSON.Net

Today we’re going to keep looking at the internals of the SharpArch.Web assembly and we’ll take a quick peek at the JsonNetResult class. This is  a custom ActionResult class which you can use if you need to return JSON serialized by the  Json.NET serializer to the client.

As you recall, custom ActionResult classes are supposed to override the ExecuteResult method in order to write the response that is sent back to the client. In this case, the code for that method is really simple: it will start by setting the content type (if none is specified on thee ContentType property, then the default “application/json” will be used), then it adjusts the content encoding (again, only if the property ContentEncoding is not null) and finally, it will serialize the contents of the Data property and write it to the output buffer of the response object. And that sums it up…

In the current release, you’ll have to instantiate it directly since there aren’t any helpers for doing that. If you intend to use this custom ActionResult frequently, then you probably should write a couple of methods for helping you out. If all your classes are inheriting form a base controller, then that would be a good place to put those methods…if you not, then probably you could create a couple of static helper methods like these:

public static class JsonNetHelpers    {
  public static JsonNetResult JsonNet(Object data) {
            return JsonNet(data, null );

  public static JsonNetResult JsonNet( Object data,String contentType ) {
            return JsonNet( data,contentType, null );

  public static JsonNetResult JsonNet( Object data, String contentType, Encoding encoding ) {
            return new JsonNetResult
                Data = data,
                ContentType = contentType,
                ContentEncoding = encoding

Notice two things about this approach:

  • if you want to set the JsonSerializerSettings, then you’ll need to save the returned ActionResult object (notice that I’m returning a JsonNetResult instance and not the base ActionResult) and access its SerializerSettings property before returning that instace from your action method;
  • I’m not using extension methods here…why? well, because there’s really not much point in adding this method to a controller  since it doesn’t interact with it…

And that’s all for today. Keep tuned for more on the S#arp framework.


~ by Luis Abreu on April 30, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: