Pages

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.

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

{

publicclass NetworkCheck

{

publicstaticbool IsInternet()

{

if (CrossConnectivity.Current.IsConnected)

{

returntrue;

}

else

{

// write your code if there is no Internet available

returnfalse;

}

}

}

}

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.

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

{

publicclass Phone

{

publicstring mobile { get; set; }

publicstring home { get; set; }

publicstring office { get; set; }

}

publicclass Contact

{

publicstring id { get; set; }

publicstring name { get; set; }

publicstring email { get; set; }

publicstring address { get; set; }

publicstring gender { get; set; }

public Phone phone { get; set; }

}

publicclass 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.

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.

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.

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

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

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...

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 ChennaiInterior Decorators in Chennai

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

About SubramanyamRaju

SubramanyamRaju is Microsoft MVP and also CsharpCorner MVP from the city Hyderabad, India. He is having good experience on various Microsoft Technologies about Windows 10 UWP, Windows, Windows Phone, XAML, C#, Cordova, Android, Xamarin, Mobile WebService, Visual Studio, Swift beginner and also QlikSense Tool Analyser . He is also one of the blogger where he is always very happy to share his mobility experience to others. He is a very active member in various Microsoft Communities and UG member from Hyderabad.