WP7 Rest … The Easy Way

Over and over again, I see developers that have this great idea for an application that pulls cool data from a  great services BUT get tied up in the implementation of “Getting It Done”.  So I thought I would show you a quick and easy way to get REST data from a service, transfer the JSON data to a POCO list and Bind it to a listbox.  (In under 3 minutes)

On your Mark

Get Set


The first think you need to do is find some Data that is interesting to you.  For me, I LOVE coffee so I want to create an application that shows me all the coffee places that are near to me.  I can do this using Bing Search  http://msdn.microsoft.com/en-us/library/dd251014.aspx 

Specifically, I am going to use the PhoneBook Request part of the API that is like a Yellow Pages API.  It will give me all the business that designate themselves as “Coffee” places.

(Yes I know I am not using MVVM)

The first thing I do is Create a method called GetData() and call it from my MainPage() Constructor

  public MainPage()

        private void GetData()
            string uri = "http://api.bing.net/json.aspx?AppId=YOUR_APP_ID&Version=2.0&Market=en-US&Query=Coffee&Sources=phonebook&latitude=33.8563&longitude=-118.1232";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(uri));
            request.BeginGetResponse(new AsyncCallback(ReadCallback), request);


In GetData() the first thing I do is make a call to the BING  API. 

The first part of the call shows that I want json returned and supplies my App_ID (Removed from post)  ( You can get your own Bing API key here http://msdn.microsoft.com/en-us/library/dd251020.aspx )


Next I set the version, Market, and what I am looking for


And finally, I tell it I am looking at the phonebook part of the API and where I want to search… In this example I am hardcoding the lat/long but you would of course use the Geo Location from the phone, but I wanted to keep this simple.


Next, We then need to make the call to the service.  We will use a HttpWebRequest by passing it the URI we just created

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(uri));

And then making in the call and supplying it the CallBack method (Where the call returns to when it is finished)

request.BeginGetResponse(new AsyncCallback(ReadCallback), request);

Now here is the fun part. To work with the JSon data the is returned from this query, we need to create the class structure that represents the data…….. ugggggg what a pain right?   Nope Wrong, All we need to do is use http://json2csharp.com/    Just paste in either the JSon returned OR the URI String, and it will create the classes for you. So when I paste in my URI String above, it gives me the following.

(you can, of course, break up these classes into separate files but for now, I just pasted them at the bottom of the MainPage.xaml.cs file.)


public class Query
        public string SearchTerms { get; set; }

    public class Result
        public string Title { get; set; }
        public string Url { get; set; }
        public string Business { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string StateOrProvince { get; set; }
        public string CountryOrRegion { get; set; }
        public string PostalCode { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public string UniqueId { get; set; }
        public string DisplayUrl { get; set; }

    public class Phonebook
        public int Total { get; set; }
        public int Offset { get; set; }
        public string LocalSerpUrl { get; set; }
        public string Title { get; set; }
        public List<Restuarnt> Results { get; set; }

    public class SearchResponse
        public string Version { get; set; }
        public Query Query { get; set; }
        public Phonebook Phonebook { get; set; }

    public class RootObject
        public SearchResponse SearchResponse { get; set; }

Now that you have the classes that hold the json that is returned, all you need to do is create the ReadCallback Method (Defined above)

private void ReadCallback(IAsyncResult asynchronousResult) 
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); 
            using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream())) 
                string resultString = streamReader1.ReadToEnd(); 
                var ser = new DataContractJsonSerializer(typeof(RootObject));

                var stream = new MemoryStream(Encoding.Unicode.GetBytes(resultString));
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
                RootObject myBook = (RootObject)jsonSerializer.ReadObject(stream);

                Deployment.Current.Dispatcher.BeginInvoke(() => coffeeShops.ItemsSource = myBook.SearchResponse.Phonebook.Results); 

You can see that we use a stream reader to read the results and then use a DataContractJsonSerializer to add the data to the RootObject (Root Object is one of the classes that were created for us that encapsulates all the others)

On the last line, I marshall the data to the UI thread using Dispatcher.BeginInvoke and bind it to a ListBox called coffeeShops.

That’s IT….

Now it took me 30 minutes to write this up, but it should take you only 3 minutes to implement.

Enjoy Smile