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

Advertisemen

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

      Advertisemen

      Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

      Tidak ada komentar:

      Posting Komentar

      © Copyright 2017 Tutorial Unity 3D