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

Tags: .NET, AJAX, Ajax.NET, JSON, Source Code, Web 2.0

Yesterday night I build an example on how to use Yahoo! Web Services with the AjaxPro JSON parser. The example will call a Yahoo! Web Service with output type set to JSON (see 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(
   "" +
   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();


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 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.

1 Comment

Comments have been disabled for this content.


In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: DieApfelFamilie