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: ,


Sunday, April 12, 2009

 

Don’t use UriTemplate = "/MethodName/Param1/{Param1}/Param2/{JsonObject} for Json input with WCF Service

When building Ajax-enabled WCF service that expect a Json object as input then the following would not work

[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Methodname/jsonvariable/{jsonvariable}/param2/{param2}")]
public void MethodName(string jsonvariable, string param2)
{
 
}

Where jsonvariable is a json object passed through jQuery (or ASP.NET Ajax) to a WCF service that looks like this


[{"Name":"za","Email":zubairdotnet@hotmail.com}]


After spending a while I figured out that the following UriTemplate should be used instead


 



[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Methodname/?jsonvariable={jsonvariable}&param2={param2}")]
public void MethodName(string jsonvariable, string param2)
{
 
}

Labels: , ,


This page is powered by Blogger. Isn't yours?