views:

39

answers:

2

I have a server side operation manually generating some json response. Within the json is a property that contains a string value.

What is the easiest way to escape the string value contained within this json result?

So this

string result = "{ \"propName\" : '" + (" *** \\\"Hello World!\\\" ***") + "' }";

would turn into

string result = "{ \"propName\" : '" + SomeJsonConverter.EscapeString(" *** \\\"Hello World!\\\" ***") + "' }";

and result in the following json

{ \"propName\" : '*** \"Hello World!\" ***' }
A: 

First of all I find the idea to implement serialization manually not good. You should to do this mostla only for studying purpose or of you have other very important reason why you can not use standard .NET classes (for example use have to use .NET 1.0-3.0 and not higher).

Now back to your code. The results which you produce currently are not in JSON format. You should place the property name and property value in double quotas:

{ "propName" : "*** \"Hello World!\" ***" }

How you can read on http://www.json.org/ the double quota in not only character which must be escaped. The backslash character also must be escaped. You cen verify you JSON results on http://www.jsonlint.com/.

If you implement deserialization also manually you should know that there are more characters which can be escaped abbitionally to \" and \\: \/, \b, \f, \n, \r, \t and \u which follows to 4 hexadecimal digits.

How I wrote at the beginning of my answer, it is better to use standard .NET classes like DataContractJsonSerializer or JavaScriptSerializer. If you have to use .NET 2.0 and not higher you can use Json.NET.

Oleg
Thanks for the response. I may just have to go with the built in serialization. Reason for not doing so initially was amount of extra code to implement and seemed like overkill at the time. String concatenation (in this case) was the simplest and least friction to do initially. Note: I edited the question based on your feedback about the property names (good point)
Jason Jarrett
In your answer, the link to JavaScriptSerializer is not working
Jason Jarrett
@Jason Jarrett: Thanks, the link is fixed.
Oleg
A: 

You may try something like:

string.replace(/(\\|")/g, "\\$1").replace("\n", "\\n").replace("\r", "\\r");
Edgar Bonet