Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Consume JSON Service with Windows Phone

DZone's Guide to

Consume JSON Service with Windows Phone

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

In this article I will talk about consuming JSON service in Windows Phone.


Windows Phone - JSON Service


Let's write code:


Step 1: Create a WCF Service Application.


Windows Phone - JSON WCF Service


Step 2: Create ServiceContract in IService1.


// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.

[ServiceContract]
public interface IService1
{
   [OperationContract]
   [WebGet(UriTemplate = "GetCustomerDetails", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
   Customer[] GetCustomerDetails();
}

Step 3: Create DataContract in IService1.

[DataContract]
public class Customer
{
   [DataMember]
   public int CustomerId { get; set; }
   [DataMember]
   public string CustomerName { get; set; }
}

Step 4: Add GetCustomerDetails method in Service1.svc.cs.

public Customer[] GetCustomerDetails()
{
   return new Customer[] 
   {
      new Customer() {CustomerId=100,CustomerName="Cust 1",},
      new Customer() {CustomerId=102,CustomerName="Cust 2"},
      new Customer() {CustomerId=103,CustomerName="Cust 3"},
      new Customer() {CustomerId=104,CustomerName="Cust 4"},
      new Customer() {CustomerId=105,CustomerName="Cust 5"},
      new Customer() {CustomerId=106,CustomerName="Cust 6"},
      new Customer() {CustomerId=107,CustomerName="Cust 7"},
      new Customer() {CustomerId=108,CustomerName="Cust 8"}
   };
}

Step 5: Open Web.Config and place below serviceModel tag.

<system.serviceModel>
   <services>
      <service name="JSON_Service.Service1">
         <endpoint name="jsonEP" address="" binding="webHttpBinding" behaviorConfiguration="json" contract="JSON_Service.IService1"/>
      </service>
   </services>
   <behaviors>
      <endpointBehaviors>
         <behavior name="json">
            <webHttp/>
         </behavior>
      </endpointBehaviors>
   </behaviors>
   <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

Service is ready, now we will create Windows Phone application to consume JSON Service data.

Step 6: Create a Silverlight for Windows Phone project.

Step 7: Place Grid RowDefinition, Button, TextBlock and ListBox inside ContentPanel in MainPage.XAML.

<Grid.RowDefinitions>
   <RowDefinition></RowDefinition>
   <RowDefinition></RowDefinition>
   <RowDefinition></RowDefinition>
   <RowDefinition></RowDefinition>
</Grid.RowDefinitions>

<Button x:Name="btnGetData" Grid.Row="0" Height="75" Content="Get JSON Data" Click="btnGetData_Click" />
<TextBlock Text="Customer ID Customer Name" Height="50" Grid.Row="1" FontSize="22" FontWeight="Bold" TextAlignment="Left" Foreground="#FFFFB090"></TextBlock>
<ListBox Name="lstCustomer" Grid.Row="2" FontSize="24">
</ListBox>

Step 8: Create a Class Customer.

 

public class Customer
{
   public int CustomerId { get; set; }
   public string CustomerName { get; set; }
}

Step 9: Place btnGetData_Click method in MainPage.Xaml.cs which will invoked on click of Get JSON Data Button.

void btnGetData_Click(object sender, RoutedEventArgs e)
{
   try
   {
      WebClient webClient = new WebClient();
      Uri uri = new Uri("http://localhost:4611/Service1.svc/GetCustomerDetails");
      webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
      webClient.OpenReadAsync(uri);
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
}

 

Step 10: Add reference of System.Servicemode.Web and System.Xml.Linq.


Windows Phone - JSON Add Reference


Step 11: Add below using directive in MainPage.Xaml.cs.

using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;

Step 12: webClient_OpenReadCompleted method will be invoked when service read operation is completed. Place below method in MainPage.Xaml.cs.

void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
   DataContractJsonSerializer ser = null;
   try
   {
      ser = new DataContractJsonSerializer(typeof(ObservableCollection<Customer>));
      ObservableCollection<Customer> customers = ser.ReadObject(e.Result) as ObservableCollection<Customer>;
      foreach (Customer em in customers)
      {
         int customerId = em.CustomerId;
         string customerName = em.CustomerName;
         lstCustomer.Items.Add(customerId + " " + customerName);
      }
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
}

Step 13: Now run the Windows Phone application and click on Get JSON Data. If service is not running servie needs to be hosted.

This ends the article of Consuming JSON in Windows Phone.

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:

Published at DZone with permission of Sumit Dutta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}