How to fix "Uncaught SyntaxError: Unexptected token L in JSON at position 1"
How to fix "Uncaught SyntaxError: Unexptected token L in JSON at position 1"
我有 JavaScript
函数,其中使用了 JSON
解析器:
function myFunction(jobj) {
jobj = JSON.parse(jobj);
console.log("jobj: ", jobj);
}
我有 2 个应用程序(一个 Visual Studio C# 应用程序和一个 Android Studio 应用程序)带有 WebView "myWebView",我在其中调用 JavaScript 函数 "myFunction":
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));
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 + "')");
在 C# 中工作正常。
但是在 Android 中,当我进行解析时,我收到错误消息:
Uncaught SyntaxError: Unexptected token L in JSON at position 1
谢谢,最诚挚的问候菲尔
在 Android 中,您使用的是 Java。当您在 Java 中使用连接运算符时,操作数将变成一个字符串。但是,您正在连接 jsonArray
,它是一个数组 — 而数组的字符串表示是神秘的。例如,new String[] { "foo", "bar" };
字符串化为 "[Ljava.lang.String;@2a139a55"
, 而不是 ["foo", "bar"]
,就像在大多数合理的语言中一样。您可以将 jsonArray
替换为
"[" + String.join(", ", jsonArray) + "]"
我有 JavaScript
函数,其中使用了 JSON
解析器:
function myFunction(jobj) {
jobj = JSON.parse(jobj);
console.log("jobj: ", jobj);
}
我有 2 个应用程序(一个 Visual Studio C# 应用程序和一个 Android Studio 应用程序)带有 WebView "myWebView",我在其中调用 JavaScript 函数 "myFunction":
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));
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 + "')");
在 C# 中工作正常。
但是在 Android 中,当我进行解析时,我收到错误消息:
Uncaught SyntaxError: Unexptected token L in JSON at position 1
谢谢,最诚挚的问候菲尔
在 Android 中,您使用的是 Java。当您在 Java 中使用连接运算符时,操作数将变成一个字符串。但是,您正在连接 jsonArray
,它是一个数组 — 而数组的字符串表示是神秘的。例如,new String[] { "foo", "bar" };
字符串化为 "[Ljava.lang.String;@2a139a55"
, 而不是 ["foo", "bar"]
,就像在大多数合理的语言中一样。您可以将 jsonArray
替换为
"[" + String.join(", ", jsonArray) + "]"