Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft.Json SerializeObject without escape backslashes

Tags:

json

c#

json.net

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"} 
like image 480
morleyc Avatar asked Dec 01 '13 14:12

morleyc


2 Answers

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; } 
like image 191
devRyan Avatar answered Sep 26 '22 09:09

devRyan


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.

like image 27
S52 Avatar answered Sep 26 '22 09:09

S52