This is not exactly a Xamarin-specific problem so apologies if this is not the right place for it!
I'm building an Android and iPhone application that shows a WebView
(UIWebView
on iOS). The WebView
has an HTML page loaded in it which contains a simple JavaScript function defined as follows:
function parseJson(input) { alert("start of parseJson(...) JavaScript method"); var parsedJson = JSON.parse(input); alert("end of parseJson(...) JavaScript method"); }
What I want to do is to call my parseJson(input)
JavaScript function from the Android/iOS client passing in a string
as the input parameter. This is done as follows for Xamarin.Android:
string json = "{}" myWebView.LoadUrl ("javascript:parseJson(\" + json + \")"));
And as follows for Xamarin.iOS:
string json = "{}" myWebView.EvaluateJavascript ("parseJson(\" + json + \")");
Up to here, this works fine. No problem. The JavaScript function is called and executes. Also, I know I have to double-escape the quotation-mark character in my string
, as follows:
string json = "{\\\"key\\\":\\\"value\\\"}";
This also works fine. The JavaScript function is called and executes. Double escaping "\r"
and "\n"
(to "\\\r"
and "\\\n"
) also works. However, if the JSON string contains a "\\"
, "\b"
, "\t"
or "\f"
, then the JSON.parse(...)
call in my JavaScript function falls over (even if the character is double-escaped).
Anyone here ever encountered this or a similar problem and know how I can reliably escape my JSON string from within the client before I feed it into my JavaScript function?
Posts
You can find the RFC here: http://www.ietf.org/rfc/rfc4627.txt
Section 2.5 discusses the details of string escaping in JSON.
You can also look at the implementation of the quote function (line 945) in the link below. I believe it does exactly what you want to do:
http://grepcode.com/file/repo1.maven.org/maven2/org.codehaus.jettison/jettison/1.3.3/org/codehaus/jettison/json/JSONObject.java#JSONObject
Thanks Peter. Very useful.
I made some progress with this. I posted my answer on Stack Overflow here for anyone interested:
http://stackoverflow.com/a/23224442/1071320
Whilst not a complete, definitive answer, it'll get you started escaping the most common special characters.