c# - without - newtonsoft json trim




Newtonsoft.Json SerializeObject without escape backslashes (4)

Given the code:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

The output is below:

"{\"Bar\":\"something\"}"

When debugging a large json document it is hard to read - using the built in features of Newtonsoft.Json (not regex or hacks that could break things) is there any way to make the output a string with the valie:

{Bar: "something"}

Hey I Just simply write out put to a file

 using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"jsonGonna.txt", true))
        {
            file.WriteLine(json);
        }

now just run the program and you will get without black slash and it good for big programs where you need to save JSON multiple times


If this happens to you while returning the value from a WebApi method, try returning the object itself, instead of serializing the object and returning the json string. WebApi will serialize objects to json in the response by default; if you return a string, it will escape any double quotes it finds.

So instead of:

public string Get()
{
    ExpandoObject foo = new ExpandoObject();
    foo.Bar = "something";
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
    return json;
}

Try:

public ExpandoObject Get()
{
    ExpandoObject foo = new ExpandoObject();
    foo.Bar = "something";
    return foo;
}

Its Just simple make the return IHttpActionResult and return the object

  public IHttpActionResult Get()
    {

        ExpandoObject foo = new ExpandoObject();
        foo = //query result

        return ok(foo)
    }

Old question but I found this,

In my case, I was looking at the JSON string in a debugger and I found that was adding the escaping.

And when I printed JSON to console, it was without escape characters. Hope it helps.







json.net