Jason Jarrett
Jason Jarrett

Reputation: 3987

escaping string for json result in asp.net server side operation

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!\" ***' }

Upvotes: 0

Views: 2927

Answers (2)

Oleg
Oleg

Reputation: 221997

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.

Upvotes: 1

Edgar Bonet
Edgar Bonet

Reputation: 3566

You may try something like:

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

Upvotes: 0

Related Questions