Android

Android和网页进行js交互的时候,json传参问题

2018-02-09  本文已影响608人  靛蓝小孩

(1):json 传参

如果网页调用安卓的方法,并且传递的参数为json格式的字符串,

例如: var json = {"name":"乔布斯","age":24,"company":"苹果公司"};

直接将json作为参数传递:window.jsInterface.invokeMethod(json
);

这样,安卓端获取的参数不可用,打印出来是undefinded

网页中一定要这样处理一下,再作为参数传递:

var jsonStr = JSON.stringify(json);

window.jsInterface.invokeMethod(jsonStr);

这样,安卓端才能获取到json的字符串,创建出json的对象进行解析。

(2):eg

h5写法:
method1:
window.messageHandlers.pushServeDetail("10001");

method2:
var json = {"specCode":specCode,"specPrice":specPrice,"specDesc":specDesc};
var jsonStr = JSON.stringify(json);
window.messageHandlers.selectProfiles(jsonStr)

android 端的写法:

//messageHandlers:h5 端定义的方法,JSInterface 是Android 自己定义的类,h5 的所有方法都可以写在这个类中
mBaseWebView.addJavascriptInterface(new JSInterface(), "messageHandlers");

public class JSInterface {
@JavascriptInterface
public void pushServeDetail(String productCode) {//productCode 是h5 传递过来的参数,pushServeDetail 是h5与Android 约定好的方法
Logger.d("------", productCode);
Bundle bundle = new Bundle();
bundle.putString("productCode", productCode);
bundle.putString("productName", "时时看护");
JumpUtils.startActivity(mContext, ProductMainActivity.class, bundle);
}

    @JavascriptInterface
    public void selectProfiles(String string) {//selectProfiles 是h5与Android 约定好的方法,里面的参数是json 字符串,h5 需要上方的写法进行传递

        if (string != null) {
            try {
                KindBean bean = GsonUtils.jsonToBean(string, KindBean.class);

                Intent intent = new Intent(mContext, WaitOrderDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("kindBean", bean);
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();

            } catch (Exception e) {

            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读