Monday, May 2, 2011

WCF DataServices and JSON format

WCF data services by default uses the response type as XML in ATOM format. I thought there will be some configuration in web.config to change the response type to JSON. You really don't have to do anything in the web.config to change the response type. All you need to do is two things.

1. Set the response type to JSON on WEBGet method of your data service as shown below.

[WebGet(ResponseFormat = WebMessageFormat.Json)]
public IQueryable<Test> GetTests()
{
var tests = BuildTests();
return tests.AsQueryable();
}


2. On the client side while requesting a data service set the HTTP header "Accept" with a value "application/json"

Your data service will now returns JSON as a response to the request.

No comments: