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.
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.
- namespace RestDemo.Model
- {
- public class NetworkCheck
- {
- public static bool IsInternet()
- {
- if (CrossConnectivity.Current.IsConnected)
- {
- return true;
- }
- else
- {
- // write your code if there is no Internet available
- return false;
- }
- }
- }
- }
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.
- public async void GetJSON()
- {
- // Check network status
- if (NetworkCheck.IsInternet())
- {
- var client = new System.Net.Http.HttpClient();
- var response = await client.GetAsync("REPLACE YOUR JSON URL");
- string contactsJson = await response.Content.ReadAsStringAsync(); //Getting response
- }
- }
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.
- {
- "contacts": [{
- "id": "c200",
- "name": "Ravi Tamada",
- "email": "ravi@gmail.com",
- "address": "xx-xx-xxxx,x - street, x - country",
- "gender": "male",
- "phone": {
- "mobile": "+91 0000000000",
- "home": "00 000000",
- "office": "00 000000"
- }
- }]
- }
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"
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace RestDemo.Model
- {
- public class Phone
- {
- public string mobile { get; set; }
- public string home { get; set; }
- public string office { get; set; }
- }
- public class Contact
- {
- public string id { get; set; }
- public string name { get; set; }
- public string email { get; set; }
- public string address { get; set; }
- public string gender { get; set; }
- public Phone phone { get; set; }
- }
- public class ContactList
- {
- public List<Contact> contacts { get; set; }
- }
- }
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.
- public async void GetJSON()
- {
- //Check network status
- if (NetworkCheck.IsInternet())
- {
- var client = new System.Net.Http.HttpClient();
- var response = await client.GetAsync("REPLACE YOUR JSON URL");
- string contactsJson = await response.Content.ReadAsStringAsync();
- ContactList ObjContactList = new ContactList();
- if (contactsJson != "")
- {
- //Converting JSON Array Objects into generic list
- ObjContactList = JsonConvert.DeserializeObject<ContactList>(contactsJson);
- }
- //Binding listview with server response
- listviewConacts.ItemsSource = ObjContactList.contacts;
- }
- else
- {
- await DisplayAlert("JSONParsing", "No network is available.", "Ok");
- }
- //Hide loader after server response
- ProgressLoader.IsVisible = false;
- }
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.
- {
- "contacts": [{
- "id": "c200",
- "name": "Ravi Tamada",
- "email": "ravi@gmail.com",
- "address": "xx-xx-xxxx,x - street, x - country",
- "gender": "male",
- "phone": {
- "mobile": "+91 0000000000",
- "home": "00 000000",
- "office": "00 000000"
- }
- },
- {
- "id": "c201",
- "name": "Johnny Depp",
- "email": "johnny_depp@gmail.com",
- "address": "xx-xx-xxxx,x - street, x - country",
- "gender": "male",
- "phone": {
- "mobile": "+91 0000000000",
- "home": "00 000000",
- "office": "00 000000"
- }
- },
- {
- "id": "c202",
- "name": "Leonardo Dicaprio",
- "email": "leonardo_dicaprio@gmail.com",
- "address": "xx-xx-xxxx,x - street, x - country",
- "gender": "male",
- "phone": {
- "mobile": "+91 0000000000",
- "home": "00 000000",
- "office": "00 000000"
- }
- }
- ]
- }
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).
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="RestDemo.Views.JsonParsingPage">
- <Grid>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
- <Label Grid.Row="0" Margin="10" Text="JSON Parsing" FontSize="25" />
- <ListView x:Name="listviewConacts" Grid.Row="1" HorizontalOptions="FillAndExpand" HasUnevenRows="True" ItemSelected="listviewContacts_ItemSelected">
- <ListView.ItemTemplate>
- <DataTemplate>
- <ViewCell>
- <Grid HorizontalOptions="FillAndExpand" Padding="10">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- </Grid.RowDefinitions>
- <Label Text="{Binding name}" HorizontalOptions="StartAndExpand" Grid.Row="0" TextColor="Blue" FontAttributes="Bold"/>
- <Label Text="{Binding email}" HorizontalOptions="StartAndExpand" Grid.Row="1" TextColor="Orange" FontAttributes="Bold"/>
- <Label Text="{Binding phone.mobile}" HorizontalOptions="StartAndExpand" Grid.Row="2" TextColor="Gray" FontAttributes="Bold"/>
- <BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" Grid.Row="3" HorizontalOptions="FillAndExpand" />
- </Grid>
- </ViewCell>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- </Grid>
- <ActivityIndicator x:Name="ProgressLoader" IsRunning="True"/>
- </Grid>
- </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)
- //Binding listview with server response
- 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.
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.
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
ReplyDeleteMaxMunus 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/
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
ReplyDeleteThank 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.
ReplyDeleteGD Goenka Rohini
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.
ReplyDeleteAndroid Training in Chennai
CCNA Training in Chennai
Cognos Training in Chennai
Very Interesting information shared than other blogs
ReplyDeleteThanks for Sharing and Keep updating us
Nice information regarding JSON parsing My sincere thanks for sharing this post Please Continue to share this post
ReplyDeleteDot Net Training in Chennai
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.
ReplyDeletedot net training in chennai
TIA.
ReplyDeletehi 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...
Very Interesting information shared than other blogs. Thanks for Sharing and Keep updating us. Xamarin development India
ReplyDeletenice 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.
ReplyDeletesoftware testing training in chennai
This comment has been removed by the author.
ReplyDeleteThanks for sharing such an informative blog. You described it nicely. Quality writing.
ReplyDeletexamarin mobile application development for android
Very helpful suggestions that help in the optimizing topic,Thanks for your sharing.
ReplyDeleteหนังฝรั่งแอคชั่น
I get error as "your app has entered a break state" after trying to run this line ,
ReplyDeletevar response =await client.GetAsync("http://api.androidhive.info/contacts/");
what am i missing ?
I get the same error at the same line of code.
DeleteAwe-inspiring bequest! Your site is actually attention-grabbing. Personally i think love for this.
ReplyDeleteUSA mobile app developers
hi there very nice article keep it up
ReplyDeleteApp Mobile Development in the App Store with More Feature
Thanks for sharing such an informative blog. You described it nicely. Quality writing.
ReplyDeleteWeb Development Company in Navi Mumbai
Interesting and Useful Information Thankyou so much
ReplyDeletePMP Chennai
Gud Nice Information.ms dynamics crm online training
ReplyDeleteThanks for this post :)
ReplyDeleteCan you show us, how did you create the webservice and where schould i save the api in my server?
Thanks!! Very useful!! :D
ReplyDeleteThanks for sharing this article....
ReplyDeleteInterior Designers in Chennai
Top Interior Decorators in Chennai
Thanks for sharing this type of Windows App Development Tutorial...
ReplyDeleteInterior Designers in Chennai
Interior Decorators in Chennai
Interior Design in Chennai
Where to find xamarin developers - Inwizards is a Xamarin Development Company offers you to hire xamarin developers for xamarin mobile app development services.
ReplyDeleteXamarin services India
xamarin development company
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.
ReplyDeleteBase SAS Training in chennai
Thank u for your information and get more new update your page For More Details:Find Girls, Search Bride,Check Your Life Partner,SecondMarriageMatrimony.
ReplyDeletenice 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.
ReplyDeletexamarin development company
hire xamarin developer india
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.
ReplyDeleteLogistics management software
Oil and gas ERP
RFID Solutions
Human resources management software
Thanks for sharing, but i have a doubt. In this line: ObjContactList = JsonConvert.DeserializeObject(contacts); Is (contacts) or (response)?
ReplyDeleteThank 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.
ReplyDeleteGlad to hear that :)
DeleteHey Subbu,
ReplyDeleteNice 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.
ERROR> The name 'contacts' does not exist in the current context
ReplyDeleteDid you added below class in your model folder??
Deletepublic class ContactList
{
public List contacts { get; set; }
}
I am getting an error at this point bjContactList = JsonConvert.DeserializeObject(contacts); . Actually I am using products as in the Model as follows
ReplyDeletepublic 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
You have to change objProdluctList = JsonConvert.DeserializeObject(records); to objProdluctList = JsonConvert.DeserializeObject(productsJason);
DeleteI am getting an error @ ObjContactList = JsonConvert.DeserializeObject(contacts);
ReplyDeleteI 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; }
}
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.
ReplyDelete1. 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.
Yes, you are right and made changes. Thank you so much :)
Delete