ASP.NET – Converting C# String to JSON String
Most web applications display messages to users. Displaying messages is the most effective way to inform user about errors and warnings or to simply display info or success status.
I also believe that most of those web applications renders user messages using HTML elements such as Div, Span or Label.
Those of you that already faced this problem won’t learn nothing new but I hope to alert the others and avoid them to face a problem that usually is only detected in advanced develop stage or even production environment.
Typically the characters are “ and ‘ but there are more.
By now, you should be thinking that your applications are immune to this problem. Tell me, do you use string Resources? Most of us use, it’s a best practice and a smart choice. Also tell me, do you manage production string Resources? Most of us don’t. In fact, the application owner or sponsor can change it completely outside of your control scope.
String Resources are one of the major vectors of this problem but you can get this problem simply by trying to display an exception message:
What we are needing is an JScript.Encode method or similar that encode a C# string in such a way that it becomes a JSON encoded string.
Such method is not available on NetFX but, fortunately, Rick Strahl made a great post about this problem and made available a method that fits perfectly our needs.
Now that you know about it … use it.