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>(contacts);  
  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

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  :)

25 comments:

  1. Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting. So know it's helpful..

    Hadoop Training in Chennai

    Base SAS Training in Chennai

    ReplyDelete
  2. 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
  3. This is extremely great information for these blog!! And Very good work. It is very interesting to learn from to easy understood. Thank you for giving information. Please let us know and more information get post to link.

    Oracle Training in Chennai

    ReplyDelete
  4. 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
  5. 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
  6. 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
  7. Very Interesting information shared than other blogs
    Thanks for Sharing and Keep updating us

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

    ReplyDelete
  9. 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
  10. 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
  11. It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions.You can write next articles referring to this article. I desire to read even more things about it..
    Office Interiors in Chennai
    Interior Decorators in Chennai

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

    ReplyDelete
  13. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  14. 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
  15. This comment has been removed by the author.

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

    xamarin mobile application development for android

    ReplyDelete
  17. Really Good blog post.provided a helpful information.I hope that you will post more updates like this.
    Digital marketing company in Chennai

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

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

    ReplyDelete
  19. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    mcdonaldsgutscheine.net/ | startlr.com/ | saludlimpia.com/

    ReplyDelete
  20. 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
  21. Awe-inspiring bequest! Your site is actually attention-grabbing. Personally i think love for this.
    USA mobile app developers

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

    ReplyDelete
  23. If you need your ex-girlfriend or ex-boyfriend to come crawling back to you on their knees (no matter why you broke up) you need to watch this video
    right away...

    (VIDEO) Win your ex back with TEXT messages?

    ReplyDelete

Search Engine Submission - AddMe