June 23, 2015

Requesting REST Webservice with JSON in C# Xamarin Android

In Brief: Webservice is an integral part of Mobile application development. To build any dynamic application web service is must and should. In simple word it is like bridge for the communication between client and server.  In this post i will explain how to build app with REST web service.

In Detail:
Here i will build the example application that requests yahoo weather server for the weather forecast information via REST request.
Yahoo weather server returns response in JSON format which is then need to be deserialize back to class object.
This is all about client side functionality for rest request consume in xamarin.android.
Before going further let us look at about the term "REST" and "JSON".
Representational state transfer[REST] is a Architectural style and not a protocol unlike SOAP.
  • Widely Accepted because of simplicity and compatibility.
  • Makes use of Hypertext Transfer Protocol(HTTP) (with the HTTP verbs (GET, POST, PUT, DELETE))for the communication with the server.
  • Very similar to Web browser, by knowing the entry point[URL] one can traverse through the webpage.
  • Platform and Language independent.
  • Limited bandwidth and resources.
Javascript object notation [JSON] is  the recommended format for the structured data transfer.
  • JSON has the ability to exchange data in non-primitive type like Arrays and Objects, in addition to primitive types like number,strings etc. 
  • JSON is more light-weight than XML.
  • Faster parsing.
Proceeding to web-service request, i will make use of Webclient class to do this. here you may have the question why not HttpWebRequest. 
Because this does the same functionality as HttpWebRequest. In-fact WebClient is a higher level abstraction built on a top of HttpWebRequest. [refer for more: http://stackoverflow.com/questions/4988286/what-difference-is-there-between-webclient-and-httpwebrequest-classes-in-net] 
If you need more control over the request(like if you need to add request.Method,request.ContentType ) then HttpWebRequest is preferable.

Code Snippet:
a)Request yahoo REST web-service to return response in JSON format.
      const string strYahooApi=  "https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select
      woeid from geo.places(1) where text='{0}') and u='c'format=json";
       string strUri=  string.Format ( strYahooApi , "New York");
        //Download string using webclient object
            var webclient = new WebClient ();
            string strResultData;
                strResultData=  webclient.DownloadString (new System.Uri(strUri));             }
                Toast.MakeText ( this , "Unable to connect to server!!!" , ToastLength.Short ).Show (); 
                webclient.Dispose ();   //dispose webclient object
                webclient = null; 
b) Parse the JSON string response to Class object.
Here i will make use of xamarin  component "Newtonsoft.Json" for the JSON parsing. [Add component to project]
Generate the csharp class from JSON string received, this can be done by using online tool [like http://json2csharp.com].
Explore the complete code here Git. 
    WeatherClass objYahooWeatherClass = JsonConvert.DeserializeObject <WeatherClass> ( strResultData );
    //for example
    List <Forecast> lstForeCast=objYahooWeatherClass.query.results.channel.item.forecast;

That's all.. now the expected data is in class object and we can play with this data as per our requirement.
Here i have written the code snippet just to highlight the  concept. When making an web-request need to check this,
  •   Internet connectivity check
  •   Run downloading process to background [DownloadStringTaskAsync]
  •   Avoid inline assignment.
FinalTouchThis is all about making use of REST web-service.
Comment me if you have any suggestion/better way of doing this or bug out of this steps/code.
Happiee coding ... :)