Google Xamarin.Forms: Consuming Rest Webservice - JSON Parsing (C# - Xaml) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Monday, 17 April 2017

Xamarin.Forms: Consuming Rest Webservice - JSON Parsing (C# - Xaml)

Introduction:
Previously we learned XML parsing in Xamarin.Forms. And this article demonstrates how to consume a RESTful web service and how to parse the JSON response from a Xamarin.Forms application.




Requirements:
  • This article source code is prepared by using Visual Studio 2017 Enterprise. And it is better to install latest visual studio updates from here.
  • This article is prepared on a Windows 10 machine.
  • This sample project is Xamarin.Forms PCL project.
  • This sample app is targeted for Android, iOS & Windows 10 UWP. And tested for Android & UWP only. Hope this sample source code would work for iOS as well.
Description:
This article can explain you below topics:
1. How to create Xamarin.Forms PCL project with Visual studio 2017?
2. How to check network status from Xamarin.Forms app?
3. How to consuming webservice from Xamarin.Forms?
4. How to parse JSON string?
5. How to bind JSON response to ListView?
Let's learn how to use Visual Studio 2017 to create Xamarin.Forms project.

1. How to create Xamarin.Forms PCL project with Visual studio 2017?
Before to consume webservice, first we need to create the new project. 
  • Launch Visual Studio 2017/2015.
  • On the File menu, select New > Project.
  • The New Project dialog appears. The left pane of the dialog lets you select the type of templates to display. In the left pane, expand Installed Templates Visual C# > Cross-Platform. The dialog's center pane displays a list of project templates for Xamarin cross platform apps.
  • In the center pane, select the Cross Platform App (Xamarin.Forms or Native) template. In the Name text box, type "RestDemo". Click OK to create the project.
  • And in next dialog, select Blank App=>Xamarin.Forms=>PCL.The selected App template creates a minimal mobile app that compiles and runs but contains no user interface controls or data. You add controls to the app over the course of this tutorial.
  • Next dialog will ask for you to confirm that your UWP app support min & target versions. For this sample, I target the app with minimum version 10.0.10240 like below:
2. How to check network status from Xamarin.Forms app?
Before call webservice, first we need to check internet connectivity of a device, which can be either mobile data or Wi-Fi. In Xamarin.Forms, we are creating cross platform apps, so the different platforms have different implementations. 
So to check the internet connection in Xamarin.Forms app, we need to follow the steps given below.
Step 1:
Go to solution explorer and right click on your solution=>Manage NuGet Packages for solution.

Now search for Xam.Plugin.Connectivity NuGet package. On the right side, make sure select all platform projects and install it.


Step 2:
In Android platform, you have to allow the user permission to check internet connectivity. For this, use the steps given below.
Right click on RestDemo.Android Project and select Properties => Android Manifest option. Select ACCESS_NETWORK_STATE and INTERNET permission under Required permissions.




Step 3:
Create a class name "NetworkCheck.cs", and here I placed it in the Model folder. After creating a class, add below method to find network status.
  1. namespace RestDemo.Model    
  2. {    
  3.     public class NetworkCheck    
  4.     {    
  5.         public static bool IsInternet()    
  6.         {    
  7.             if (CrossConnectivity.Current.IsConnected)    
  8.             {    
  9.                 return true;    
  10.             }    
  11.             else    
  12.             {    
  13.                 // write your code if there is no Internet available      
  14.                 return false;    
  15.             }    
  16.         }    
  17.     }    
  18. }  
3. How to consuming webservice from Xamarin.Forms?

We can consume webservice in Xamarin using HttpClient. But it is not directly available, and so we need to add "Microsoft.Net.Http" from Nuget.



Step 1: Go to solution explorer and right click on your solution=>Manage NuGet Packages for a solution => search for Microsoft.Net.Http NuGet Package=>on the right side, make sure select all platform projects and install it.




Note: To add "Microsoft.Net.Http", you must install "Microsoft.Bcl.Build" from Nuget. Otherwise, you will get an error like "Could not install package 'Microsoft.Bcl.Build 1.0.14'. You are trying to install this package into a project that targets 'Xamarin.iOS,Version=v1.0', but the package does not contain any assembly references or content files that are compatible with that framework."




Step 2:

Now it is time to use HttpClient for consuming webservice and before that we need to check the network connection. Please note that In below code you need to replace your URL, or you can also find the demo webservice url from the source code given below about this article.
  1. public async void GetJSON()  
  2.         {  
  3.             // Check network status  
  4.             if (NetworkCheck.IsInternet())  
  5.             {  
  6.                 var client = new System.Net.Http.HttpClient();  
  7.                 var response = await client.GetAsync("REPLACE YOUR JSON URL");  
  8.                 string contactsJson = await response.Content.ReadAsStringAsync(); //Getting response  
  9.             }  
  10.         }  
4. How to parse JSON response string in Xamarin.Forms?
Generally, we will get a response from webservice in the form of XML/JSON. And we need to parse them to show them on mobile app UI. Let's assume, in the above code we will get below sample JSON response which is having a list of contacts.
  1. {  
  2.     "contacts": [{  
  3.         "id": "c200",  
  4.         "name": "Ravi Tamada",  
  5.         "email": "ravi@gmail.com",  
  6.         "address": "xx-xx-xxxx,x - street, x - country",  
  7.         "gender": "male",  
  8.         "phone": {  
  9.             "mobile": "+91 0000000000",  
  10.             "home": "00 000000",  
  11.             "office": "00 000000"  
  12.         }  
  13.   
  14.     }]  
  15. }  
So to parse above JSON, we need to follow steps below:

Step 1: First we need to generate the C#.net class for JSON response string. So I am using http://json2csharp.com/ for simply building a C# class from a JSON string. And it's very important is to make the class members as similar to JSON objects otherwise you will never parse JSON properly. Finally, I generate below the C# root class name is "ContactList"
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace RestDemo.Model  
  8. {  
  9.     public class Phone  
  10.     {  
  11.         public string mobile { getset; }  
  12.         public string home { getset; }  
  13.         public string office { getset; }  
  14.     }  
  15.   
  16.     public class Contact  
  17.     {  
  18.         public string id { getset; }  
  19.         public string name { getset; }  
  20.         public string email { getset; }  
  21.         public string address { getset; }  
  22.         public string gender { getset; }  
  23.         public Phone phone { getset; }  
  24.     }  
  25.   
  26.     public class ContactList  
  27.     {  
  28.         public List<Contact> contacts { getset; }  
  29.     }  
  30. }  

Step 2: In Xamarin, we need to add "Newtonsoft.Json" Nuget package to parse JSON string. So to add Newtonsoft.Json, go to solution explorer and right click on your solution=>select Manage NuGet Packages for a solution => search for Newtonsoft.Json NuGet Package=>on the right side, make sure select all platform projects and install it.

Step 3: And finally, write below code to parse above JSON response.
  1. public async void GetJSON()  
  2.         {  
  3.             //Check network status   
  4.             if (NetworkCheck.IsInternet())  
  5.             {  
  6.                
  7.                 var client = new System.Net.Http.HttpClient();  
  8.                 var response = await client.GetAsync("REPLACE YOUR JSON URL");  
  9.                 string contactsJson = await response.Content.ReadAsStringAsync();  
  10.                 ContactList ObjContactList = new ContactList();  
  11.                 if (contactsJson != "")  
  12.                 {  
  13.                     //Converting JSON Array Objects into generic list  
  14.                     ObjContactList = JsonConvert.DeserializeObject<ContactList>(contactsJson);  
  15.                 }  
  16.                 //Binding listview with server response    
  17.                 listviewConacts.ItemsSource = ObjContactList.contacts;  
  18.             }  
  19.             else  
  20.             {  
  21.                 await DisplayAlert("JSONParsing""No network is available.""Ok");  
  22.             }  
  23.             //Hide loader after server response    
  24.             ProgressLoader.IsVisible = false;  
  25.         } 
5. How to bind JSON response to ListView?

Generally, it is very common scenario is showing a list of items in ListView from the server response.
Let's assume we have below JSON response from the server via webservice.
  1. {  
  2.     "contacts": [{  
  3.             "id""c200",  
  4.             "name""Ravi Tamada",  
  5.             "email""ravi@gmail.com",  
  6.             "address""xx-xx-xxxx,x - street, x - country",  
  7.             "gender""male",  
  8.             "phone": {  
  9.                 "mobile""+91 0000000000",  
  10.                 "home""00 000000",  
  11.                 "office""00 000000"  
  12.             }  
  13.         },  
  14.         {  
  15.             "id""c201",  
  16.             "name""Johnny Depp",  
  17.             "email""johnny_depp@gmail.com",  
  18.             "address""xx-xx-xxxx,x - street, x - country",  
  19.             "gender""male",  
  20.             "phone": {  
  21.                 "mobile""+91 0000000000",  
  22.                 "home""00 000000",  
  23.                 "office""00 000000"  
  24.             }  
  25.         },  
  26.         {  
  27.             "id""c202",  
  28.             "name""Leonardo Dicaprio",  
  29.             "email""leonardo_dicaprio@gmail.com",  
  30.             "address""xx-xx-xxxx,x - street, x - country",  
  31.             "gender""male",  
  32.             "phone": {  
  33.                 "mobile""+91 0000000000",  
  34.                 "home""00 000000",  
  35.                 "office""00 000000"  
  36.             }  
  37.   
  38.         }  
  39.     ]  
  40. }  
See there is 3 different items in above JSON response and if we want to plan for showing them in ListView first we need to add below Xaml code in your ContentPage(JsonParsingPage.xaml).
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              x:Class="RestDemo.Views.JsonParsingPage">  
  5.     <Grid>  
  6.         <Grid>  
  7.             <Grid.RowDefinitions>  
  8.                 <RowDefinition Height="Auto"/>  
  9.                 <RowDefinition Height="*"/>  
  10.             </Grid.RowDefinitions>  
  11.             <Label Grid.Row="0" Margin="10" Text="JSON Parsing" FontSize="25" />  
  12.             <ListView x:Name="listviewConacts" Grid.Row="1" HorizontalOptions="FillAndExpand" HasUnevenRows="True" ItemSelected="listviewContacts_ItemSelected">  
  13.                 <ListView.ItemTemplate>  
  14.                     <DataTemplate>  
  15.                         <ViewCell>  
  16.                             <Grid HorizontalOptions="FillAndExpand" Padding="10">  
  17.                                 <Grid.RowDefinitions>  
  18.                                     <RowDefinition Height="Auto"/>  
  19.                                     <RowDefinition Height="Auto"/>  
  20.                                     <RowDefinition Height="Auto"/>  
  21.                                     <RowDefinition Height="Auto"/>  
  22.                                 </Grid.RowDefinitions>  
  23.                                 <Label Text="{Binding name}" HorizontalOptions="StartAndExpand" Grid.Row="0" TextColor="Blue"  FontAttributes="Bold"/>  
  24.                                 <Label Text="{Binding email}" HorizontalOptions="StartAndExpand" Grid.Row="1" TextColor="Orange"  FontAttributes="Bold"/>  
  25.                                 <Label Text="{Binding phone.mobile}" HorizontalOptions="StartAndExpand" Grid.Row="2" TextColor="Gray"  FontAttributes="Bold"/>  
  26.   
  27.                                 <BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" Grid.Row="3" HorizontalOptions="FillAndExpand" />  
  28.                             </Grid>  
  29.                         </ViewCell>  
  30.   
  31.                     </DataTemplate>  
  32.                 </ListView.ItemTemplate>  
  33.             </ListView>  
  34.         </Grid>  
  35.         <ActivityIndicator x:Name="ProgressLoader" IsRunning="True"/>  
  36.     </Grid>  
  37. </ContentPage>  
See in above code there is a ListView which was binded with relevant properties (name, email, mobile) which was mentioned in our class name called Contact.cs.
Finally, we need to bind our ListView with list like below:(Please find which was already mentioned in the 4th section of GetXML method at 17th line)
  1.  //Binding listview with server response    
  2.                 listviewConacts.ItemsSource = ObjContactList.contacts;  


Demo Screens from Android:


Demo Screens from Windows10 UWP:



You can directly work on below sample source code that is having the functionality of JSON parsing. 
JSONParsingSample
You can also see overview of this article from below youtube video. For more videos please don't forget to SUBSCRIBE our youtube channel from here.


Note: If you are looking for XML parsing sample, please visit here.

FeedBack Note: Please share your thoughts, what you think about this post, Is this post really helpful for you? Otherwise, it would be very happy, if you have any thoughts for to implement this requirement in any other way? I always welcome if you drop comments on this post and it would be impressive.

Follow me always at @Subramanyam_B
Have a nice day by  :)

40 comments:

  1. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in QLIKSENSE, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor led training on QLIKSENSE. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us.
    Avishek Priyadarshi
    MaxMunus
    E-mail: avishek@maxmunus.com
    Skype id: avishek_2 .
    Ph:(0) 8553177744 / 080 - 41103383
    http://www.maxmunus.com/

    ReplyDelete
  2. This is extremely helpful info!! Very good work. Everything is very interesting to learn and easy to understood. Thank you for giving information. Good Work. Keep it up! Android Runtime Permissions

    ReplyDelete
  3. Thank you for sharing such a nice and interesting blog with us. Online Public School. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle.
    GD Goenka Rohini

    ReplyDelete
  4. This idea is mind blowing. I think everyone should know such information like you have described on this post. Thank you for sharing this explanation.Your final conclusion was good. We are sowing seeds and need to be patiently wait till it blossoms.
    Android Training in Chennai
    CCNA Training in Chennai
    Cognos Training in Chennai

    ReplyDelete
  5. Very Interesting information shared than other blogs
    Thanks for Sharing and Keep updating us

    ReplyDelete
  6. Nice information regarding JSON parsing My sincere thanks for sharing this post Please Continue to share this post
    Dot Net Training in Chennai

    ReplyDelete
  7. really nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now got some knowledge. so keep on sharing such kind of an interesting blogs.
    dot net training in chennai

    ReplyDelete
  8. TIA.
    hi you are doing a great job here.as am working SAP type project from past years and now i have to deal with PCL. So in PCL calling webAPI is a bit tricky can u res-post the code with below changes.that would be very helpful to me.
    what if we want to send some token with headers and parameter and what if we want send image bytes to server.how can we do that.
    Here there is no timeout option available or any kind of exception is not handled ServicePointManager.ServerCertificateValidationCallback is also not available...

    ReplyDelete
  9. Very Interesting information shared than other blogs. Thanks for Sharing and Keep updating us. Xamarin development India

    ReplyDelete
  10. nice blog has been shared by you.before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blog.
    software testing training in chennai

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Thanks for sharing such an informative blog. You described it nicely. Quality writing.

    xamarin mobile application development for android

    ReplyDelete
  13. Very helpful suggestions that help in the optimizing topic,Thanks for your sharing.

    หนังฝรั่งแอคชั่น

    ReplyDelete
  14. I get error as "your app has entered a break state" after trying to run this line ,
    var response =await client.GetAsync("http://api.androidhive.info/contacts/");

    what am i missing ?

    ReplyDelete
    Replies
    1. I get the same error at the same line of code.

      Delete
  15. Awe-inspiring bequest! Your site is actually attention-grabbing. Personally i think love for this.
    USA mobile app developers

    ReplyDelete
  16. Thanks for sharing such an informative blog. You described it nicely. Quality writing.
    Web Development Company in Navi Mumbai

    ReplyDelete
  17. Interesting and Useful Information Thankyou so much
    PMP Chennai

    ReplyDelete
  18. Thanks for this post :)
    Can you show us, how did you create the webservice and where schould i save the api in my server?

    ReplyDelete
  19. Where to find xamarin developers - Inwizards is a Xamarin Development Company offers you to hire xamarin developers for xamarin mobile app development services.
    Xamarin services India
    xamarin development company

    ReplyDelete
  20. this is very nice post and thanks for sharing this wonderful information to us.i really would like to appreciate to your attention for us.

    Base SAS Training in chennai

    ReplyDelete
  21. Thank u for your information and get more new update your page For More Details:Find Girls, Search Bride,Check Your Life Partner,SecondMarriageMatrimony.

    ReplyDelete
  22. nice blog has been shared by you.before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blog.
    xamarin development company
    hire xamarin developer india

    ReplyDelete
  23. I do believe all of the concepts you’ve introduced in your post. They’re very convincing and will definitely work. Nonetheless, the posts are too short for novices. May you please extend them a bit from subsequent time? Thank you for the post.
    Logistics management software
    Oil and gas ERP
    RFID Solutions
    Human resources management software

    ReplyDelete
  24. Thanks for sharing, but i have a doubt. In this line: ObjContactList = JsonConvert.DeserializeObject(contacts); Is (contacts) or (response)?

    ReplyDelete
  25. Thank you very much, congratulations for making a good practice, I based on your project to use it with a weather ApiRest, when I finish it I share it.

    ReplyDelete
  26. Hey Subbu,
    Nice tutorial but i am getting some error like Package 'Micrsoft.Net.Http' was restored using the .Netframework version =v4.6.1 instead of the target framework of '.NetStandard , version=v2.0'

    Are you sure you made this application in VS2017 as we dont get the option for PCL in VS2017. we get the option for .Net Standard instead of PCL.

    do you have any option to convert this .NetStandard to .NetFramework i tried but then the xamarin forms are becoming obsolete.

    ReplyDelete
  27. ERROR> The name 'contacts' does not exist in the current context

    ReplyDelete
    Replies
    1. Did you added below class in your model folder??
      public class ContactList
      {
      public List contacts { get; set; }
      }

      Delete
  28. I am getting an error at this point bjContactList = JsonConvert.DeserializeObject(contacts); . Actually I am using products as in the Model as follows
    public class Record
    {
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string price { get; set; }
    public string category_id { get; set; }
    public string category_name { get; set; }
    }

    //public class RootObject
    public class RecordList
    {
    public List records { get; set; }
    }
    My getJason in MainPage.xaml.cs as follows
    public async void GetJSON()
    {
    //Check network status
    if (NetworkCheck.IsInternet())
    {

    var client = new System.Net.Http.HttpClient();
    var response = await client.GetAsync("http://10.0.2.2:9090/api/objects/read.php");
    string productsJason = await response.Content.ReadAsStringAsync();
    RecordList objProdluctList = new RecordList();
    if (productsJason != "")
    {
    //Converting JSON Array Objects into generic list
    objProdluctList = JsonConvert.DeserializeObject(records);
    }
    //Binding listview with server response
    listviewConacts.ItemsSource = objProdluctList.records;
    }
    else
    {
    await DisplayAlert("JSONParsing", "No network is available.", "Ok");
    }
    //Hide loader after server response
    ProgressLoader.IsVisible = false;
    }
    ERROR : The name 'records' does not exist in the current context RestDemo1

    ReplyDelete
    Replies
    1. You have to change objProdluctList = JsonConvert.DeserializeObject(records); to objProdluctList = JsonConvert.DeserializeObject(productsJason);

      Delete
  29. I am getting an error @ ObjContactList = JsonConvert.DeserializeObject(contacts);
    I made a change in the class names where contacts becomes records
    changes as follows
    public async void GetJSON()
    {
    //Check network status
    if (NetworkCheck.IsInternet())
    {

    var client = new System.Net.Http.HttpClient();
    var response = await client.GetAsync("http://10.0.2.2:9090/api/objects/read.php");
    string productsJason = await response.Content.ReadAsStringAsync();
    RecordList objProdluctList = new RecordList();
    if (productsJason != "")
    {
    //Converting JSON Array Objects into generic list
    objProdluctList = JsonConvert.DeserializeObject(records);
    }
    //Binding listview with server response
    listviewConacts.ItemsSource = objProdluctList.records;
    }
    else
    {
    await DisplayAlert("JSONParsing", "No network is available.", "Ok");
    }
    //Hide loader after server response
    ProgressLoader.IsVisible = false;
    }

    and the model is follows
    public class Record
    {
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string price { get; set; }
    public string category_id { get; set; }
    public string category_name { get; set; }
    }

    //public class RootObject
    public class RecordList
    {
    public List records { get; set; }
    }

    ReplyDelete
  30. Thanks a lot Subramanyam Raju. For 2 days I have been trying to get an understanding on webservices & Jason deserialization.Yours is the best and simplest way to understand. Only one issue in this which I faced and want others to know.
    1. I changed the contact to product.
    2. Webservice returns the data in Jason format as {"products":[{"id":"60","name":"Rolex Watch","description":"Luxury watch.","price":"25000","category_id":"1","category_name":"Fashion"},
    IT IS VERY IMPORTANT that the class has a products list as public List products { get; set; }
    3. I assume that there should be change in your code line as follows :
    ObjContactList = JsonConvert.DeserializeObject(contacts);
    SHOUD BE CHANGED TO contactsJson as ObjContactList = JsonConvert.DeserializeObject(contactsJson );
    Please correct me if I am wrong.
    Other wise your blog is the best to follow.
    Thanks once again.

    ReplyDelete
    Replies
    1. Yes, you are right and made changes. Thank you so much :)

      Delete

Search Engine Submission - AddMe