Google Search API with Silverlight and System.Json
There are many ways to handle JSON in .NET, this approach uses a weakly-typed approach, which makes the parsing more flexible to schema changes. I wanted to try the Microsoft approach and use System.JSON – This is all from a .NET 4 environment in Silverlight, with a non-blocking behaviour.
So, from the highest level, this is how I wanted the method to act. – from MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
GoogleSearch.DoSearch(“Hello”, Callback);
}private void Callback(List<GoogleSearchResult> googleSearchResults)
{
// to-do
}
So, in a separate class, I defined a GoogleSearchResult as follows:
public class GoogleSearchResult
{
public string Title;
public Uri Url;
}
Then, to make a HTTP call to the Google custom search API as follows:
public static void DoSearch(string query, Action<List<GoogleSearchResult>> callback)
{
var strUrl = “https://www.googleapis.com/customsearch/v1?”;
strUrl += “q=” + query;
strUrl += “&cx=…”;
strUrl += “&key=…..”;
var wc = new WebClient();
wc.DownloadStringAsync(new Uri(strUrl), callback);
wc.DownloadStringCompleted += DownloadStringCompleted;
}
Then defining the DownloadStringCompleted method as follows:
static void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var callback = (Action<List<GoogleSearchResult>>) e.UserState;
var json = JsonValue.Parse(e.Result);
if (json == null || (json[“items”] as JsonArray) == null)
{
callback(null);
return;
}
var lResults = json[“items”].Cast<JsonObject>().Select(jo =>
new GoogleSearchResult
{
Title = jo[“title”],
Url = new Uri(jo[“link”])
}).ToList();
callback(lResults);
}
Notice how the callback function is passed through in the UserState (same as userToken)