Wednesday, April 15, 2009
Return JSON objects the right way
Today I experienced a weird behavior when I was passing JSON string back to a jQuery call using an Ajax-enabled WCF Service.
My code looked something like this.
[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetJson")]
public string GetJson()
{
return new JavaScriptSerializer().Serialize(MyCustomObject)
}
The problem with above code is that the string returned is escaped and enclosed with inverted commas that for some reason was not handled properly using jQuery that looked like this.
“[{\"Id\":1,\"SomeKey\":\"SomeMoreText\"}]”
Not sure what I was missing and while there is a JsonResult action in ASP.NET MVC with a .svc there’s nothing that I could use (or may be there is).
To fix it I changed the method like this.
[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetJson")]
public System.IO.Stream GetJson()
{
byte[] resultBytes = System.Text.Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(MyCustomObject));
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
return new MemoryStream(resultBytes);
}
Here’s how Json is returned.
[{"Id":1,"SomeKey":"SomeMoreText"}]
Labels: jquery, WCF Service