Royi Namir
Royi Namir

Reputation: 148524

Json Escaping using JavaScriptSerializer Class?

Im using the JavaScriptSerializer Class to serilize and Deserilize in/to Json.

I know there is a json.net library out there.

But My question is :

Can I also use JavaScriptSerializer class to escape my json string ?

or should I do it myself ? and if so should I do it by encodeURIComponent ?

Upvotes: 1

Views: 5456

Answers (2)

John Gibb
John Gibb

Reputation: 10773

Yes, it's an appropriate way to safely encode a string. Just call serialize on your string.

To be more clear, if you look into the actual JavaScriptSerializer implementation (I'm using dotpeek), you can see that it actually calls this function:

private static void SerializeString(string input, StringBuilder sb)
{
  sb.Append('"');
  sb.Append(HttpUtility.JavaScriptStringEncode(input));
  sb.Append('"');
}

So I guess another answer is that you can just use HttpUtility.JavaScriptStringEncode, although it won't add the double quotes around it.

Upvotes: 5

competent_tech
competent_tech

Reputation: 44931

The answer to your question depends on how you are using the json.

If you are sending out via an ajax call, then you probably don't need to do anything with the string.

If you are embedding the resulting json in a javascript variable from codebehind, then you only need minimal escaping to ensure the js is correctly formatted. This is what we use for this:

sJsonString = sJsonString.Replace("\r\n", "\\r\\n")

(Sorry, that is VB code, may need some adjustment for C#)

I think this may be the appropriate C# code:

sJsonString = sJsonString.Replace("\\r\\n", "\\\\r\\\\n");

Upvotes: 0

Related Questions