【问题标题】:Android - Passing JSON object from webview javascript to javaAndroid - 将 JSON 对象从 webview javascript 传递到 java
【发布时间】:2014-03-28 10:35:29
【问题描述】:

我在 java 端有一个带有 webview 和 javascript 接口的 Activity。我想用 Java 编写一个可以接受来自 webview 的 json 参数的方法。

@JavascriptInterface
public String test(Object data) {
    Log.d("TEST", "data = " + data);
}

在我的 webview javascript 上我调用:

MyAPI.test({ a: 1, b: 2 });

但数据变量为空。

如何将 JSON 对象从 webview javascript 传递到本机方法?

谢谢

【问题讨论】:

  • 你只能传递字符串和原语。

标签: javascript android json webview


【解决方案1】:

@njzk2 是对的,这样做:

在 JAVA 中:

@JavascriptInterface
public String test(String data) {
   Log.d("TEST", "data = " + data);
   return "this is just a test";
}

在 JS 中:

// some code 
var result = test("{ a: 1, b: 2 }");
alert(result);
//some code

function test(args) {
   if (typeof Android != "undefined"){ // check the bridge 
      if (Android.test!= "undefined") { // check the method
         Android.test(args);
      }
   }
}

【讨论】:

    【解决方案2】:

    您可以使用 GSON 库或类似的库来创建字符串化 JSON 到 Java 对象,并在 JS 端使用 JSON.Stringify(data)

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 2023-03-25
      • 2011-06-21
      相关资源
      最近更新 更多