I have JavaScript
function where a JSON
parser is used:
function myFunction(jobj) {
jobj = JSON.parse(jobj);
console.log("jobj: ", jobj);
}
I have 2 apps (one Visual Studio C# app and one Android Studio app) with a WebView "myWebView" where I call the JavaScript function "myFunction":
Code in C#
JObject jobj = new JObject();
jobj.Add("id", "testId");
jobj.Add("value", "1234");
String json = jobj.ToString(Newtonsoft.Json.Formatting.None, null);
String[]jsonArray = new String[] { json };
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => await myWebView.InvokeScriptAsync("myFunction", jsonArray));
Code in Android:
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", "testId");
jsonObj.put("value", "1234");
String json = jsonObj.toString();
String[]jsonArray = new String[] { json };
myWebView.loadUrl("javascript:myFunction('" + jsonArray + "')");
In C# it's working fine.
But in Android when I do the parse I get the error message:
Uncaught SyntaxError: Unexptected token L in JSON at position 1
Thanks, best regards Phil
In Android you're using Java. When you use the concatenation operator in Java, the operand is turned into a string. However, you are concatenating jsonArray
, which is an array — and arrays' string representation is cryptic. For example, new String[] { "foo", "bar" };
stringifies as "[Ljava.lang.String;@2a139a55"
, not ["foo", "bar"]
as it would in most sensible languages. You might replace jsonArray
there with
"[" + String.join(", ", jsonArray) + "]"