Yahoo! Web Services Request and AjaxPro JSON Parser - I love it!

Michael Schwarz on Tuesday, July 11, 2006

Yesterday night I build an example on how to use Yahoo! Web Services [1] with the AjaxPro JSON parser [2]. The example will call a Yahoo! Web Service with output type set to JSON (see http://developer.yahoo.com/common/json.html [3]). The response will be deserialized to an .NET structure using the AjaxPro JSON parser (from the stand-alone version or the build-in parser in Ajax.NET Professional).

First of all I have to get the response from the Web Service using the WebRequest class:

string query = "Madonna";    // demo search for "Madonna"
int count = 5;

WebRequest request = WebRequest.Create( "http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query [4]=" + query + "&results=" + count + "&output=json" );

request.Credentials = CredentialCache.DefaultCredentials;

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream);

string responseFromServer = reader.ReadToEnd();

reader.Close(); dataStream.Close(); response.Close();

Now, I have to deserialize the JSON response string to an .NET data type. I can simply generate an IJavaScriptObject from the JSON string and go to all properties. But today I'd like to get a real .NET class. I had a look on the result XML schema [5] and build my own structures that will represent the results from the Yahoo! Web Service:

struct YahooResponse
{
public YahooResultSet ResultSet;
}

struct YahooResultSet { public int totalResultsAvailable; public int totalResultsReturned; public int firstResultPosition; public YahooResult[] Result; }

struct YahooResult { public string Title; public string Summary; public string Url; public string ClickUrl; public string RefererUrl; public string FileSize; public string FileFormat; public int Height; public int Width; public YahooThumbnail Thumbnail; }

struct YahooThumbnail { public string Url; public int Height; public int Width; }

The next line will create a YahooResponse object from the JSON string...

YahooResponse r = JavaScriptDeserializer.DeserializeFromJson<YahooResponse>(responseFromServer);

...and allowes me to go through the result set with .NET data types. What do you think?

Console.WriteLine(r.ResultSet.totalResultsAvailable + " Results");

foreach (YahooResult s in r.ResultSet.Result) { Console.WriteLine("\t " + s.Title); Console.WriteLine("\t    format: " + s.FileFormat); Console.WriteLine("\t      size: " + s.Width + " x " + s.Height); }

Note: Did you noticed the generic DeserializeFromJson method which is new to the current release?

Update: Download example project from the Google group thread [6].