Returning raw json (string) in wcf Returning raw json (string) in wcf json json

Returning raw json (string) in wcf


Currently your web method return a String together with ResponseFormat = WebMessageFormat.Json. It follow to the JSON encoding of the string. Corresponds to www.json.org all double quotes in the string will be escaped using backslash. So you have currently double JSON encoding.

The easiest way to return any kind of data is to change the output type of GetCurrentCart() web method to Stream or Message (from System.ServiceModel.Channels) instead of String.
See http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx, http://msdn.microsoft.com/en-us/library/ms789010.aspx and http://msdn.microsoft.com/en-us/library/cc681221(VS.90).aspx for code examples.

Because you don't wrote in your question which version of .NET you use, I suggest you to use an universal and the easiest way:

public Stream GetCurrentCart(){    //Code ommited    var j = new { Content = response.Content, Display=response.Display,                  SubTotal=response.SubTotal};    var s = new JavaScriptSerializer();    string jsonClient = s.Serialize(j);    WebOperationContext.Current.OutgoingResponse.ContentType =        "application/json; charset=utf-8";    return new MemoryStream(Encoding.UTF8.GetBytes(jsonClient));}


I tried the method suggested by Oleg but found that when i used this method for a large amount of data null key word was appended at the end of the JSON string.

Example: for json with lots of data{"JsonExample":"xxxxx"}null

found a solution to address this problem at : http://wcf.codeplex.com/workitem/67Wrote the following function which will accept a object and return a Pure Json output. So before returning my object in the main method i make a call to the below method.

  public HttpResponseMessage ReturnPureJson(object responseModel)    {        HttpResponseMessage response = new HttpResponseMessage();        string jsonClient = Json.Encode(responseModel);        byte[] resultBytes = Encoding.UTF8.GetBytes(jsonClient);        response.Content = new StreamContent(new MemoryStream(resultBytes));        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");        return response;    }


That was great (Oleg Response) and all make sure that you add the line WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

if you removed it result will be downloaded as file .