Adam
Adam

Reputation: 41

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

Upvotes: 4

Views: 8442

Answers (3)

Tx3
Tx3

Reputation: 6916

What you're seeing is a escape character

Your JSON is a String and when you want to have " in a string you must use one of the following:

string alias = @"My alias is ""Tx3""";

or

string alias = "My alias is \"Tx3\"";

Update

Just to clarify. What I wanted say here is that your JSON is perfectly valid. You're seeing the special characters in the IDE and that is perfectly normal like Jon & Marc are pointing in their answers and comments. Problem lies somewhere else than those \ characters.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062745

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

Upvotes: 7

GLlompart
GLlompart

Reputation: 271

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

Upvotes: 2

Related Questions