1

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 ?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just what I needed! And there is an overload that takes an extra argument that will optionally add the outer double quotes.
0

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

1 Comment

However, don't forget to escape double quotes!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.