JSON from JObject creates '\r' and '\n' characters. How do I remove?

Jul 13, 2009 at 3:48 AM


Just downloaded the latest Json35b4 dlls.  I was trying to use the Linq to JSON feature and it is working fine except for one thing.  I am using JQuery's .ajax method to call the web service which returns the JSON string.  It reads it as:

{"d":"{\r\n  \"models\": [\r\n    {\r\n      \"manufacturerId\": 12,\r\n      \"modelId\": 1,\r\n   
\"modelName\": \"Axiom\",\r\n \"modelInfo\": null\r\n }\r\n ]\r\n}"}

As you can see there are a lot of escape characters in it and I cannot read the object correctly.

Is it because of the formatting created by the JObject? If I access the web service page directly, I get this:

  "models": [
      "manufacturerId": 12,
      "modelId": 1,
      "modelName": "Axiom",
      "modelInfo": null

How do I get rid of all these extra characters? Please help.

Here's my JQuery call:

$.populateModels = function(value)
   if (value !== 0)  {
        var json = "{'manufacturerId' : " + value + "}";
        type: "POST",
        url: "/Services/ModelTracker.asmx/GetModelsJSON",
        data: json,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: $.populateModelsSuccess


Jul 13, 2009 at 5:28 AM

The problem is the JSON that Json.NET is producing is being escaped by the webservice. It is being stuffed into a string which is the value of property d.

{"d":"escaped Json.NET content here"}

Oct 14, 2009 at 10:54 AM

I get the same thing. What is the solution? Do we have to write code to strip out these escape characters? And why does the <string> element appear? Currently I am returning the JSON in  string. I did try and parse it into a JObject, but I am confused in that JObject.Parse() will not accept a string as a parameter.

My AJAX call is similar to the above example, and my .Net code is as follows;

    public string GetBusinessLevelTiers()
            string json = JsonConvert.SerializeObject(BOL.blTiers, Formatting.Indented,
                new JsonSerializerSettings {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects });
            string json1 = json.Replace("\r\n", string.Empty);
            return json1;
        catch (Exception ex)
            return string.Empty;

Oct 15, 2009 at 3:44 AM

The string element is added by the web service because it needs to be XML. I described why the double encoding happens in my post above.


I don't know the solution to fix it server side while using WebMethods other than not using them and returning a raw response. You are already using Json.NET to do serialization.

The other option is to handle the not ideal response on the client.