In this article, we’ll explore the process of writing and consuming JSON services using ASP.NET, WCF, and jQuery to request stock prices for companies.
Visual Studio 2010 Web Application Project Template Additions
There are several additions to the Visual Studio 2010 Web Application Project Template that aid in working with JSON services:
- jQuery Intellisense: Helps in writing jQuery code efficiently
- AJAX-enabled WCF Service: Item template for configuring a JSON service to be consumed and proxied by an ASP.NET ScriptManager
- Targeted web.config files: Manage different service endpoints for various environments
Understanding JSON
JavaScript Object Notation (JSON) is a subset of JavaScript’s object literal notation. As JSON is a subset of JavaScript, it can be used seamlessly within the language. Here’s an example of JSON:
var dog = {color: "grey", name: "Spot", size: 46};
Comparing JSON and SOAP Services
SOAP services tend to be quite verbose, enabling tools like Visual Studio’s “Add Service Reference” to auto-generate client proxy classes. However, JSON offers a much more compact alternative. For example, consider the following XML used to request a stock price and its corresponding response:
xml
<soap:Envelope ...>
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>GOOG</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
The JSON equivalent would be much shorter:
ticker=GOOG
{"d":534.5}
Creating an AJAX-enabled WCF Service
The AJAX-enabled WCF Service item template does most of the work. However, you can take an additional step to configure the channel factory directly on the service declaration (*.svc
) file:
<%@ ServiceHost ... %>
Decorate the operation (service method) with the WebGetAttribute
to enable the use of HTTP GET for data retrieval and return the response as JSON:
csharp
[WebGet(ResponseFormat = WebMessageFormat.Json)]
The resulting stock price service’s code behind will look like this:
csharp
[ServiceContract(Namespace = JsonWcfDemoNamespace.Value)]
public class StockPriceService
{
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json)]
public StockPrice GetStockPrice(string ticker)
{
...
}
}
Working with JSON Data in JavaScript
JavaScript provides several ways to work with JSON data:
eval()
: Invokes the JavaScript compiler, which parses the text and produces an object structure. However, it can compile and execute any JavaScript code, so there might be security issues.JSON.parse()
: A safer alternative toeval()
. A JSON parser recognizes only JSON text, rejecting all scripts. In browsers with native JSON support, JSON parsers are faster thaneval()
.
Consuming JSON Services with jQuery
jQuery offers the getJSON
method for making calls to services providing JSON-formatted responses and performing the JSON conversion. The method signature is as follows:
javascript
$.getJSON( url, [ data ], [ callback(data, textStatus) ] )
To consume our stock price service using the getJSON
method:
javascript
$.getJSON("StockPriceService.svc/GetStockPrice", { ticker: tickerValue }, function (data, textStatus) {
...
});
Handling WCF Serialized JSON Dates
WCF serializes DateTime
values in JSON as /Date({milliseconds since 01/01/1970}-{time zone})/
. Native JSON conversion does not automatically convert the date string to a JavaScript Date
object. Here’s an example of how to convert a JSON date string to a JavaScript Date
object:
javascript
function convertJSONToDate(json) {
return eval(json.replace(/\/Date\((.*?)\)\//gi, "new Date($1)"));
}
With these steps and tools, we can effectively create and consume JSON services using ASP.NET, WCF, and jQuery for various applications such as requesting stock prices for companies.