14 July 2009

Using the Google AJAX Search API: JSON serialisation with .NET

Google’s AJAX Search API is designed to let you add searches to web pages via JavaScript. However, there’s nothing to stop you using .NET to execute searches on the server side.

There’s a certain cleanliness to being able to do everything on the server, and I certainly prefer not to have to do all the work in the browser. This article explains how to use the Google search API in .NET and also provides a code sample for a server-side web search that you can download (ZIP archive, 6kb)

Using the Google Search API

The API exposes a simple RESTful interface and the URLs and arguments for the different searches are documented in Google’s API reference.

The API itself is functionally limited as it is optimised to serve JavaScript-based clients. There are also a number of restrictions on what you can do with the results of a search call. You have to display results as they are delivered – no splitting, re-sorting or tweaking – and you also have to clearly state that Google is the source of the results. You’re also obliged to provide the url of the referring page when you make the API call. It’s worth having a look at Google’s terms of use to ensure that your application meets the requirements.

Working with the API is simple enough, so long as you are comfortable with working with Json in .NET.

Json serialization in .NET

WCF provides support for serializing and deserializing Json via the DataContractJsonSerializer class in the System.Runtime.Serialization.Json namespace.

The code structure is very similar as XML Serialization. Firstly, you have to create a set of data classes that reflect the structure of the Json output. The classes have to be decorated with the [DataContract] attribute and each member has to be decorated with a [DataMember] attribute.

The following is a simple example of some Json output:

{"results":[
            {"name":"John Smith","emailAddress":"test@example.com"}
            {"name":"John Smith","emailAddress":"test@example.com"}
            {"name":"John Smith","emailAddress":"test@example.com"}
       ]}

This will require two data classes – one to hold the results and another to describe each result:

[DataContract]
public class PersonList
{
    [DataMember(Name = "result")]
    public Person[] People
    { get; set; }
}

[DataContract]
public class Person
{
    [DataMember(Name = "name")]
    public string PersonName
    { get; set; }

    [DataMember(Name = "emailAddress")]
    public string EmailAddress
    { get; set; }
}

The code example is a generic deserialisation method that can be applied to any Json deserialisation:

private static T DeserialiseJson<T>(string json) where T : new()
{
    if (!string.IsNullOrEmpty(json))
    {
        byte[] respBytes = ASCIIEncoding.UTF8.GetBytes(json);
        using (StreamReader reader = new StreamReader(new MemoryStream(respBytes)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T returnObj = (T)serializer.ReadObject(reader.BaseStream);
            return returnObj;
        }
    }
    else
    {
        return new T();
    }
}

The deserialisation method would be called as follows:

PersonList data = DeserialiseJson<GoogleWebResponseData>(json);

The code sample

The sample project contains a full implementation of the Google web search service. It contains five data classes that encapsulate all the data returned from a Google web search call as well as a static class that makes the calls to the Goolge API and deserialises the results.

Download the source code (ZIP archive, 6kb)

Filed under ASP.NET, C#.