Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net 4.0 JSON Serialization: Double quotes are changed to \"

I'm using System.Web.Script.Serialization.JavaScriptSerializer() to serialize dictionary object into JSON string. I need to send this JSON string to API sitting in the cloud. However, when we serialize it, serializer replaces all the double quotes with \"

For example -

Ideal json_string = {"k":"json", "data":"yeehaw"}

Serializer messed up json_string = {\"k\":\"json\",\"data\":\"yeehaw\" }

Any idea why it is doing so? And I also used external packages like json.net but it still doesn't fix the issues.

Code -

Dictionary<string, string> json_value = new Dictionary<string, string>();
json_value.Add("k", "json");
json_value.Add("data", "yeehaw");
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json_string = jsonSerializer.Serialize(json_value);
like image 723
Adam Avatar asked Jan 17 '23 09:01

Adam


2 Answers

I'm going to hazard the guess that you're looking in the IDE at a breakpoint. In which case, there is no problem here. What you are seeing is perfectly valid JSON; simply the IDE is using the escaped string notation to display it to you. The contents of the string, however, are your "ideal" string. It uses the escaped version for various reasons:

  • so that you can correctly see and identify non-text characters like tab, carriage-return, new-line, etc
  • so that strings with lots of newlines can be displayed in a horizontal-based view
  • so that it can be clear that it is a string, i.e. "foo with \" a quote in" (the outer-quotes tell you it is a string; if the inner quote wasn't escaped it would be confusing)
  • so that you can copy/paste the value into the editor or immediate-window (etc) without having to add escaping yourself
like image 180
Marc Gravell Avatar answered Jan 23 '23 04:01

Marc Gravell


Make sure you're not double serializating the object. It happened to me some days ago.

like image 21
GLlompart Avatar answered Jan 23 '23 05:01

GLlompart