Reader Level:
ARTICLE

How to Consume WCF REST Service Returning JSON in Windows Phone 7

Posted by dj Articles | Windows Phone December 23, 2011
In this article I will show you a way to consume a JSON WCF REST Service in Windows Phone 7.
  • 0
  • 0
  • 24562

In this article I will show you a way to consume a JSON WCF REST Service in Windows Phone 7. This article is divided into four parts.

  1. Creating a simple WCF REST Service for ADD
  2. Consuming the JSON REST Service in Windows Phone 7 application.
  3. Creating a complex WCF REST Service with custom classes and types.
  4. Consuming the complex JSON REST Service in Windows Phone 7 application.

Creating a simple Add Service

To start with, let us create a WCF REST Service returning JSON as below. There is one operation contact named Add in the service and that is taking two strings as input parameters and returning an integer.
 
  [ServiceContract]
    public interface IService2
    {
        [OperationContract]
        [WebGet(UriTemplate="/Add/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
                                                       ResponseFormat = WebMessageFormat.Json
                                                       )]
        int Add(string  Number1, string Number2);
    }


The service is implemented as below:

using System;
namespace MultipleBindingWCF
{
      public class Service1 : IService2
      {
       public int Add(string Number1, string Number2)
        {
            int num1 = Convert.ToInt32(Number1);
            int num2 = Convert.ToInt32(Number2);
            return num1 + num2; 
        }
    }

Next in this section we need to configure the service. We need to configure the service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the following changes.

<?xml version="1.0"?>
<configuration>
  <
system.web>
    <
compilation debug="true" targetFramework="4.0" />
  </system.web>
  <
system.serviceModel>
    <
behaviors>
      <
serviceBehaviors>
        <
behavior name ="servicebehavior">        
          <serviceMetadata httpGetEnabled="true"/>        
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </
serviceBehaviors>
      <
endpointBehaviors>
        <
behavior name="restbehavior">
          <webHttp/>
        </
behavior>
      </
endpointBehaviors>
    </
behaviors>
    <
services>
                   <endpoint name ="RESTEndPoint"
                  contract ="MultipleBindingWCF.IService2"
                  binding ="webHttpBinding"
                  address ="rest"
                  behaviorConfiguration ="restbehavior"/>
      </service>
    </
services>   
  </
system.serviceModel>
 <
system.webServer>
    <
modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer
</
configuration>

After configuring, the service ready for hosting. You are free to host it either on Azure, IIS, or Cassini. For local ASP.Net Server hosting press F5. Do a testing of service in browser and if you are getting expected output, you are good to consume it in the Windows Phone 7 application.

Consuming the Service in Windows Phone 7

To consume the REST Service in Windows Phone 7 and then parse JSON, you need to add the following references in Windows Phone 7 project.

WCFWinPhn1.jpg

As the design of the page I have put two textboxes and one button. The user will input numbers to be added in the textbox and on click event of button result would get displayed in message box. Essentially on click event of the button we will make a call to the service. The design of the page is as below:

<Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="calling JSON REST" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="JSON REST" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBox x:Name="txtNumber1" Height="100" Margin="-6,158,6,349" />
            <TextBox x:Name="txtNumber2" Height="100" Margin="-6,28,6,479" />
            <Button x:Name="btnAdd" Height="100" Content="Add" Click="btnAdd_Click"/>
        </Grid>
    </Grid>

On click event of the button we need to make a call to the service as below:

WCFWinPhn2.jpg

And the ServiceURi is constructed as below:

WCFWinPhn3.jpg

There is nothing very fancy about the preceding service call. We are just downloading JSON as a string using WebClient. However parsing of JSON is the main focus of this article. To parse we need to write the following code in the completed event.

WCFWinPhn4.jpg

In the preceding code:

  1. Converting downloaded string as Stream

  2. Creating instance of DataContractJsonSerializer. In that we are passing type as string since returned type of service is string.

  3. Reading stream into instance of DataContractJsonSerializer

  4. Displaying the result.

Putting all code together you should have following code to make a call and parse JSON in Windows Phone 7:

using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace ConsumingJSON
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {

            string Number1 = txtNumber1.Text;
            string Number2 = txtNumber2.Text;
            string ServiceUri = "http://localhost:30576/Service1.svc/Rest/add/"
                                 + Number1 + "/"
                                 + Number2;
            WebClient proxy = new WebClient();
            proxy.DownloadStringCompleted +=
                       new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
            proxy.DownloadStringAsync(new Uri(ServiceUri));

        }

        void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
            string result = obj.ReadObject(stream).ToString();
            MessageBox.Show(result);
        }
    }
}


Creating a complex Service with custom classes and types

Go back to the service and add a custom class as below:

[DataContract]
    public class Student
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string RollNumber { get; set; }
        [DataMember]
        public string Grade { get; set; }
    }


And add one more function to the service. This operation contract will return a List of Students.

[OperationContract]
          [WebGet(UriTemplate = "/GetStudents", RequestFormat = WebMessageFormat.Json,
                                                       ResponseFormat = WebMessageFormat.Json
                                                       )]
          List<Student> GetStudents();


Next you need to implement the service as below:

  public List<Student> GetStudents()
        {
            List<Student> lstStudent = new List<Student>
            {
                 new Student { Name = "John " ,RollNumber = "1" , Grade = "A"},
                 new Student { Name = "Dan " ,RollNumber = "2" , Grade = "Q"},
                 new Student { Name = "Pinal " ,RollNumber = "3" , Grade = "M"},
                 new Student { Name = "Mahesh " ,RollNumber = "4" , Grade = "Z"},
                 new Student { Name = "Julie" ,RollNumber = "5" , Grade = "L"},
            };
            return lstStudent;
        }

Configuration will be the same as of simple REST Service returning JSON. Press F5 to host and test the service.

Consuming complex JSON REST Service in Windows Phone 7 application

At the Windows Phone 7 application, you need to create an entity class. This class will be representing the Student class of service. Add the Student class to the project as below:

public class Student
    {
        public string Name { get; set; }
        public string RollNumber { get; set; }
        public string Grade { get; set; }

    }

The design page is as below. I have used a button and upon the click event of the button, the service will be called and the returned data will be bound to the listbox.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="110" />
            </Grid.RowDefinitions>
            <ListBox x:Name="lstStudents" Height="auto" Width="auto" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}"  />
                            <TextBlock Text="{Binding RollNumber}" Style="{StaticResource PhoneTextTitle3Style}" />
                            <TextBlock Text="{Binding Grade}" Style="{StaticResource PhoneTextAccentStyle}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

            <Button Grid.Row="1" x:Name="btnAdd" Height="100" Content="Add" Click="btnAdd_Click"/>
        </Grid>

In the code behind on click event of the button we need to make call using WebClient again

private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            WebClient proxy = new WebClient();
            proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
            proxy.DownloadStringAsync(new Uri("http://localhost:30576/Service1.svc/rest/getstudents")); 

        }

And need to parse the returned JSON as below. In parameter to create instance of DataContractJsonSrrializer we are passing List of Student.

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Student>));
            List<Student> result = obj.ReadObject(stream) as List<Student>;
            lstStudents.ItemsSource = result;
        }


On running you should be getting output as below.

WCFWinPhn5.jpg
 

Article Extensions
Contents added by venu babu on Jul 28, 2012
ewrr
COMMENT USING

Trending up