In my code I must return Json string, but I can't use HtmlEncode to remove illegal character in MVC2. How can I encode a string to remove illegal JSON characters?
3 Answers
System.Web.HttpUtility.HtmlEncode() can be used without a HttpContext (using one of the existing Json libraries/classes mentioned in the other answers is probably best, but if you must do what you're asking for, then that's the method you can use)
Comments
Use the Json.NET open-source library to do your JSON reading/writing
Or you can use the built-in DataContractJsonSerializer
Comments
or use the embedded one http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx you are probably building your own json string. in that case, you'll need to implement different kinds of escaping too, not just removing illegal characters.