In this post I will show you the way to consume JSON WCF REST Service in Windows Phone 7. This post is divided into four parts.
- Creating simple WCF REST Service for ADD
- Consuming JSON REST Service in Windows Phone 7 application.
- Creating complex WCF REST Service with custom classes and types.
- Consuming complex JSON REST Service in Windows Phone 7 application.
Creating 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 integer.
[ServiceContract] public interface IService2 { [OperationContract] [WebGet(UriTemplate="/Add/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json )] int Add(string Number1, string Number2); }
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 service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the below 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, 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 Service in Windows Phone 7
To consume REST Service in Windows Phone 7 and then parse JSON, you need to add below references in Windows Phone 7 project.
As the design of the page I have put two textbox and one button. 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. 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,
And ServiceURi is constructed as below,
There is nothing much fancy about above service call. We are just downloading JSON as string using WebClient. However parsing of JSON is main focus of this post. To parse we need to write below code in completed event.
In above code
- Converting downloaded string as Stream
- Creating instance of DataContractJsonSerializer. In that we are passing type as string since returned type of service is string.
- Reading stream into instance of DataContractJsonSerializer
- Displaying the result.
Putting all code together you should have below 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 complex Service with custom classes and types
Go back to 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 service. This operation contract will return List of Students.
[OperationContract] [WebGet(UriTemplate = "/GetStudents", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json )] List<Student> GetStudents();
Next you need to implement 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 entity class. This class will be representing Student class of service. Add Student class to project as below,
public class Student { public string Name { get; set; } public string RollNumber { get; set; } public string Grade { get; set; } }
Design page as below. I have put a button and on click event of the button service will get called and returned data would be bind 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.
In this way you can work with WCF REST with JSON Data and Windows Phone 7. I hope this post is is useful. Thanks for reading
Leave a Reply