Returning Json from RESTful Interface with WCF

WCF2 Someone commented on an earlier blog post I did on REST, POX/POJO and WCF and the comment read:

How about REST WCF bits from .NET 3.5 SP1? Is it possible now to let the user decide in which format he wants the response (xml or json) like MySpace API for example?

The convention is to use a file like extension at the end of the resource to specify data return type (.xml or .json)

api.myspace.com/.../details.xml

api.myspace.com/.../details.json

UPDATE/EDIT: Turns out I was doing this the hard way as there is support for json serialization right from the ServiceContract which makes this extremely easy. Just make sure to specify the ResponseFormat to be json. In a previous "version" of this blog post, I used the JavaScriptSerializer class, which is... dumb :)

First go take a look at the sample that Kirk Evans had on his blog.

Note that it may be easier to create a RESTful interface with ASP.NET MVC if you're into that tech, but that's another blog post.

So, first I'm modifying the REST interface somewhat, adding support for /details.xml and /details.json URI:

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(UriTemplate="customers/{id}/details.xml")]
    Customer GetCustomer(string id);

    [OperationContract]
    [WebGet(UriTemplate = "customers/{id}/details.json", 
ResponseFormat=WebMessageFormat.Json)]
Customer GetJsonCustomer(string id); }

As you can see, on the GetJsonCustomer() method, I'm specifying the ResponseFormat to be json. That's it :)

A sample implementation for this interface looks like this:

public Customer GetCustomer(string id)
{
    return new Customer { ID = id, Name = "Demo User" };
}

public Customer GetJsonCustomer(string id)
{
    return GetCustomer(id);
}

Using Fiddler to simulate client request and see what comes out of our RESTful service, we get this result from the /customers/123/details.xml request:

  <Customer xmlns="http://schemas.datacontract.org/2004/07/RESTfulWCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ID>1</ID><Name>Demo User</Name></Customer>

...and this from the /customers/123/details.json request:

  {"ID":"123","Name":"Demo User"}

1 Comment

Comments have been disabled for this content.