Servicing JSON

Sometimes it is beneficial to create a RESTful service that can return a response message as either XML or JSON. Data formatted using JSON usually results in a smaller message size than data formatted as XML. JSON uses array structures to define the name and value pairs, whereas XML uses hierarchical elements. Although XML is much easier to read visually, JSON can be smaller and, thus, quicker to pass across a network.

Note

JSON is commonly used as a response format for services that Ajax clients consume.

Defining a JSON Response

Defining a set of operations that can perform the same operation but return the data as JSON or XML is very straightforward with WCF. You can set the ResponseFormat attribute to either WebMessageFormat.Xml or WebMessageFormat.Json to indicate the format of the response message. Example 9-8 shows two operations that return a Product as XML or as JSON, respectively.

Notice that the UriTemplate for the FindProductByNameAsXml method is slightly different from the UriTemplate for the FindProductbyNameAsJson method. The slight difference is enough to make the UriTemplate find a match if ?json is appended to the URI.

Example 9-8. Setting the response format

C#
// #4
[OperationContract]
[WebGet(UriTemplate = "Product/Name/{productName}",
    ResponseFormat = WebMessageFormat.Xml,
    BodyStyle = WebMessageBodyStyle.Bare)]
Product FindProductByNameAsXml(string productName);

// #5
[OperationContract]
[WebGet(UriTemplate = "Product/Name/{productName}?json",
 ResponseFormat ...

Get Data-Driven Services with Silverlight 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.