Reputation: 41
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
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
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:
"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)Upvotes: 7
Reputation: 271
Make sure you're not double serializating the object. It happened to me some days ago.
Upvotes: 2