EziData Solutions

Web, NET and SQL Server

Return JSON from WCF Web Service

JSON is a popular, light-weight method of formatting data destined for mobile devices. Many popular APIs default to JSON formatted responses, so it’s a good practice to follow.

If you are retrofitting existing WCF web services to return JSON it easy on paper, but can be painful in practice. In this post, we’ll add a JSON friendly WCF service to an existing web application and point out some of the gotchas that can make your life hell.

Firstly, add an AJAX enabled web service to your ASP.NET web application. Visual Studio will add a default web method and make a number of changes to your web config. We’re going to create a method the will return some information about places around the world, so call the web service PlaceService.

Create a simple class to represent the places, this should be in a separate cs file, but for ease of use, I’m adding it after the closing tag of our PlaceService.

Code Snippet
  1. public class Place
  2. {
  3.     public string Name { get; set; }
  4.     public string Country { get; set; }
  5.     public int Population { get; set; }
  6. }

Delete the existing DoWork method and replace it with this code GetPlaces. 

Code Snippet
  1. [ServiceContract(Namespace = "")]
  2. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  3. public class PlaceService
  4. {
  5.     [OperationContract]
  6.     [WebGet(ResponseFormat = WebMessageFormat.Json)]
  7.     public List<Place> GetPlaces()
  8.     {
  9.         // create a list of places
  10.         List<Place> places = new List<Place>();
  12.         places.Add(new Place {
  13.             Name = "London",
  14.             Country = "UK",
  15.             Population = 7825200
  16.         });
  18.         places.Add(new Place {
  19.             Name = "New York",
  20.             Country = "USA",
  21.             Population = 8175133
  22.         });
  24.         places.Add(new Place {
  25.             Name = "Sydney",
  26.             Country = "Australia",
  27.             Population = 4391674
  28.         });
  31.         // return the list of places
  32.         return places;
  33.     }
  35. }

View the page in the web browser and add the name of the method to the URL like so: http://localhost:57128/PlaceService.svc/GetPlaces 

Depending on what browser you use, you’ll either be prompted to download the JSON document, or the browser will display the JSON  directly.

{"d":[{"__type":"Place:#FileAccess.Web","Country":"UK","Name":"London","Population":7825200},{"__type":"Place:#FileAccess.Web","Country":"USA","Name":"New York","Population":8175133},{"__type":"Place:#FileAccess.Web","Country":"Australia","Name":"Sydney","Population":4391674}]}


Getting rid of the “d”

Our results are certainly JSON formatted but you’ll notice that they are wrapped in an object called “d”, short for data. Ideally, we want to get rid of the d and simply return an array of Place objects. This is done by modifying the web.config.

Sometimes it seems like configuring your web.config is a dark art, known only to a few souls. Thankfully, this change if pretty easy as all we need to do if modify the endpoint behaviour Visual Studio created for us. Look for the PlaceServiceAspNetAjaxBehavior and insert a tag to enable web HTTP. The modified config will look something like this (your namespace will be different).

Code Snippet
  1. <endpointBehaviors>
  2.   <behavior name="MyWebApplication.PlaceServiceAspNetAjaxBehavior">
  3.     <enableWebScript />
  4.     <webHttp />
  5.   </behavior>
  6. </endpointBehaviors>

Run the web service again and this time we’ll have a better response.

[{"Country":"UK","Name":"London","Population":7825200},{"Country":"USA","Name":"New York","Population":8175133},{"Country":"Australia","Name":"Sydney","Population":4391674}]   

Posted: Feb 12 2012, 01:03 by CameronM | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: ASP.NET