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));
}

Leave a Comment