Sunday, 21 November 2010

SP2010 AJAX part 4 – returning JSON from a HTTP handler

  1. Boiling jQuery down to the essentials (technique)
  2. Using the JavaScript Client OM to work with lists (technique)
  3. Using jQuery AJAX with a HTTP handler (technique)
  4. Returning JSON from a HTTP handler (technique) - this article
  5. Enable Intellisense for Client OM and jQuery (tip)
  6. Debugging jQuery/JavaScript (tip)
  7. Useful tools when building AJAX applications (tip)
  8. Migrating existing applications to jQuery/AJAX

In the last post in this series, we discussed using a HTTP handler with AJAX - a highly useful technique when building SharePoint (and plain .Net) applications which aren’t postback-heavy, and as I said I believe that’s the most important post in this series. In the example there, my HTTP handler returned a simple string saying “Returned from handler at “ + DateTime.Now() – strings are fine of course (and remember that the value returning by a HTTP handler is always a string, so we’re somewhat constrained by that) but often we want something a bit more structured. This could be for one of the following reasons:

  • You’re returning many small pieces of information from one call, and putting them in say, a separated string and then parsing on the client is, um, nasty
  • You already have an object in code on the server, and frankly it would be nice if you could just work with that on the client too

In such cases, using JSON as the format for your return data could be a good choice, and is indeed what Microsoft’s own Client OM uses. Even better, you don’t really need to know much about JSON and it’s extremely easy to use. Aside from the basic need to return structured data, some reasons why you might choose JSON (over XML for example) might be:

  • JSON is more compact than XML
  • JSON is (arguably) simpler to consume in your JavaScript than XML
  • JSON has some useful tooling support e.g. Firebug

JSON 101

JSON is JavaScript Object Notation, and is simply a format for describing name/value pairs. They can be nested too, which means it can represent reasonably complex objects - in the end it’s always one big string when it goes over the AJAX wire, but effectively it’s easy to work with at either end. To show what it looks like, consider a class like this:

public class Employee
    public int ID
    public string Name
    public Address HomeAddress
    public Salary Salary

An Employee instance represented as JSON would look like this:

{"ID":1,"Name":"Chris","HomeAddress":{"HouseNumber":55,"StreetName":"Acacia Avenue","City":"Birmingham","Postcode":"B26 8LM"},"Salary":{"Currency":"Sterling","Amount":100}}

Now clearly that looks like a horrible string to construct yourself, but of course since JSON is a common format  you don’t have to. In the same way that an object can be serialized to XML in .Net using the XmlSerializer class, you can do the same to JSON format using the JavaScriptSerializer class. To send our Employee data to the client so that the page can be updated (e.g. using the jQuery page manipulation techniques from part 1), we would use the JavaScriptSerializer class in our HTTP handler, like so:

public void ProcessRequest(HttpContext context)
    Employee emp = getEmployee();
    // serialize and send..
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    StringBuilder sbJsonResults = new StringBuilder();
    serializer.Serialize(emp, sbJsonResults);
    context.Response.ContentType = "application/json; charset=utf-8";

Note that I’m setting the MIME type of the response header to “application/json” – this enables your app and any tools to recognise the string as a JSON string, and thus potentially provide any JSON-specific support. I’ll show an example shortly of how Firebug uses this to help you see the JSON coming from the server.

Consuming JSON in JavaScript code

As we noted earlier, JSON is ideal when we are dealing with many small pieces of information, like all the properties of an Employee. In the image below, I have an area on the page with many DIVs and SPANs to present the information – these get populated when the AJAX call to the server completes:

The HTML and jQuery code to join up with the server side looks like this:

<fieldset id="fldDemo1">
    <legend>HTTP handler which returns JSON</legend>
    <div id="jsonDemo1Row" class="demoRow">
            <div class="demoControls">
                <button id="btnDemo1" type="button">Call handler</button>
            <div class="demoResults">
                <div><span class="employeeField">Employee name: </span><span id="empName" /></div>
                <div><span class="employeeField">Salary: </span></div>
                    <div><span class="employeeSubField">Amount: </span><span id="empSalaryAmount" /></div>
                    <div><span class="employeeSubField">Currency: </span><span id="empSalaryCurrency" /></div>
                <div><span class="employeeField">Address: </span></div>
                    <div><span class="employeeSubField">House number: </span><span id="empAddressHouseNumber" /></div>
                    <div><span class="employeeSubField">Street: </span><span id="empAddressStreet" /></div>
                    <div><span class="employeeSubField">City: </span><span id="empAddressCity" /></div>
                    <div><span class="employeeSubField">Postcode: </span><span id="empAddressPostcode" /></div>
<script type="text/javascript">
    $('#btnDemo1').click(function () {
        function (data) {

A couple of things to note here:

  • The JSON value is passed to the success callback of the AJAX call as the data parameter.
  • I can just use dot notation to access a property as if I was in C#/VB.Net/whatever (e.g. data.Salary.Amount) – no dodgy parsing for each value (woohoo!).
    • However, don’t expect any Intellisense here! Currently there’s no way for the tools to infer members on JavaScript objects you create yourself (jQuery and the SharePoint Client OM do it by way of a special documentation file - the next article in this series shows how to enable Intellisense for those). Given the move away from .Net web forms apps towards AJAX however, I don’t doubt that VS2013 (or whatever) may well have this.
  • Notice that jQuery has a convenient $.getJSON() method when you know that the server call is going to be returning JSON.
    • This is just like the $.get()/$.post()/$.ajax() methods we’ve looked at previously in this series, but this method performs an additional step of parsing the response to check it’s valid JSON. This let’s you handle such an error in a nice way (though note you need to use $.ajaxError() or $.ajaxSetup() to do this, rather than a failure callback on this call). Although we wouldn’t necessarily expect this to happen when we’ve used the JsonSerializer to build the JSON in the first place, in any case it’s much better than getting an obscure lower down problem e.g. when trying to get a piece of data from the Employee object.
  • The extension of my handler is .json – it doesn’t have to be, but if you’re happy to have a web.config entry (see my last article, Using jQuery AJAX with a HTTP handler for more discussion around this) then you can deviate from the standard .ashx which .Net automatically hooks up for you.

Tool support for JSON

It might not be a life-changing thing, but something very popular with developers using JSON in this way is the ‘Console’ tab in Firebug (which I briefly showed in the last article). Importantly, it allows me to see the ‘raw’ response coming back from a web service or AJAX call from the client - in the case of JSON, this is of course somewhat difficult to decipher:

However, in contrast to Fiddler or many other tools, Firebug (via the Console > JSON tab) allows you to see a nice ‘formatted’ view of your JSON object, and you can expand/contract complex properties to see their values - much easier to digest:


Final note - alternatives to JSON

Of course, JSON won’t always be the answer to passing data between the server and the client – sometimes you’ll prefer to work with XML, so here’s a good tutorial on parsing XML with jQuery.

Next time: Enable Intellisense for Client OM and jQuery (tip)


Blake Blackshear said...

I have had problems with IE caching my JSON response. I have used the $.post method to prevent this problem. Does the $.getJSON have an issue with caching?

Chris O'Brien said...


Kind of (and it's a good point) - this is basically because a web server may choose to cache any HTTP GET request, and $.getJSON and $.get fall into that category.

To prevent this, I specify 'cache:false', either in the ajax method or $.ajaxSetup.



monteirobrena said...

Thanks a lot ;)