vrijdag 8 mei 2015

How to parse Restfull webservices with JSON in Xamarin.Android

In this blogpost I'll explain how to use webservices in Xamarin.android, after creating a Restfull webservice online that can give back a JSON array or string. For example something like this:
  @"[{'Name':'Gil','Location':'A','Zone':'1','Timestamp':'2015-04-26T09:10:18.233'}]";

 As you can see the JSON string above is like a locations object, it contains the property Name, Location, Zone and Timestamp. You should use this information to create an object Locations.
The object should look like this for example:

namespace RESTtest
{
    
    public class Location
    {
        public Location ()
        {
        }

        public string Name { get; set;}
        public string Location { get; set; }
        public string Zone { get; set; }
        public string Timestamp { get; set; }


    }
}


Make sure the property's are the same in the class and in the JSON string.

After this the part where we can parse a JSON string will start. In the example below a JSON string gets parced and after that we fill a textfield with the first value of a locations name.

namespace RESTtest
{
    [Activity(Label = "WeatherREST", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            Button button = FindViewById<Button>(Resource.Id.getWeatherButton);


            TextView location = FindViewById<TextView>(Resource.Id.locationText); 
            // When the user clicks the button,  

            send the REST request to your webservice,
            button.Click += async (sender, e) => {

                // Gets the location object
                string url = "http://webservicesname.net/api/locations";

                // Fetch the information asynchronously, 

                // parse the results,
                // then update the screen:
                JsonValue json = await FetchWeatherAsync (url);
                

                List<Client> client1 = (JsonConvert.DeserializeObject<Client[]> (jsonDoc.ToString()));
               
             //we put the first value of the name into a textfield
             location.Text = client1[0].Name;             
           };
        }

        // Gets data from the passed URL.  
        private async Task<JsonValue> FetchWeatherAsync (string url)
        {
            // Create an HTTP web request using the URL:
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url));
            request.ContentType = "application/json";
            request.Method = "GET";

            // Send the request to the server and wait for the response:
            using (WebResponse response = await request.GetResponseAsync ())
            {
                // Get a stream representation of the HTTP web response:
                using (Stream stream = response.GetResponseStream ())
                {
                    // Use this stream to build a JSON document object:
                    JsonValue jsonDoc = await Task.Run (() => JsonObject.Load (stream));
                 
                    // Return the JSON document:
                    return jsonDoc;
                }
            }
        }

        
    }
}




  

2 opmerkingen: