Android与Javascript交互JSON对象

webview.loadUrl(“JavaScript:”+callbackFunction+”(‘”+data+”’)”); 这种方式将jsonobject类型的data传给js,因为js那边得到就是一个string的对象。


与此同时,js主动调用android的对象方式,android也无法返回给js一个jsonobject,需要js做一下转换,例如:


Android 代码:

  1. WebView mWebView = (WebView) this.findViewById(R.id.webview);  
  2. WebSettings settings = mWebView.getSettings();  
  3. settings.setJavaScriptEnabled(true);  
  4. settings.setPluginsEnabled(true);  
  5. settings.setAllowFileAccess(true);  
  6.   
  7. settings.setCacheMode(WebSettings.LOAD_NO_CACHE);  
  8. mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//不加上,会显示白边  
  9. String  url=”file:///android_asset/t.html”; //js代码卸载t.html里  
  10. NavigationInstance navigation =new NavigationInstance(this);  
  11. mWebView.addJavascriptInterface(navigation, ”Navigation”);  
WebView mWebView = (WebView) this.findViewById(R.id.webview);
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setPluginsEnabled(true);
settings.setAllowFileAccess(true);

settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//不加上,会显示白边
String  url="file:///android_asset/t.html"; //js代码卸载t.html里
NavigationInstance navigation =new NavigationInstance(this);
mWebView.addJavascriptInterface(navigation, "Navigation");



NavigationInstance里的代码:

  1. @Override  
  2. public JSONObject GetManeuverInfo() {  
  3. try{  
  4. JSONObject test=new JSONObject();  
  5. test.put(”maomao”“value”);  
  6. return test;  
  7. //return new JSONObject(bean.ManeuverInfo);  
  8. }catch(Exception e){  
  9. Log.e(TAG, ”“,e);  
  10. }  
  11. return null;  
  12. }  
@Override
public JSONObject GetManeuverInfo() {
try{
JSONObject test=new JSONObject();
test.put("maomao", "value");
return test;
//return new JSONObject(bean.ManeuverInfo);
}catch(Exception e){
Log.e(TAG, "",e);
}
return null;
}




t.html里的代码:

[javascript] view plain copy
print?
  1. function testAPI(el){  
  2.     console.log(”———testAPI———”);  
  3.     eval(”var obj = ”+Navigation.GetManeuverInfo());   
  4.       
  5.     alert(’typeof:’+typeof(obj));  
  6.     alert(’maomao:’+obj.maomao);  
  7.     alert(’obj:’+obj);  
  8.   }  
        function testAPI(el){
            console.log("---------testAPI---------");
            eval("var obj = "+Navigation.GetManeuverInfo()); 

            alert('typeof:'+typeof(obj));
            alert('maomao:'+obj.maomao);
            alert('obj:'+obj);
          }

如果直接写成  Navigation.GetManeuverInfo.maomao是会提示undefined,因为js那边只得到了一个string对象而已,它不知道maomao是个key。

通过eval将其转化成表达式就可以调用obj.maomao得到value。


在此ps一下iOS,貌似人家支持webview很好,js可以直接获取到json对象.



默认t.html加载会自动执行testAPI函数,结果如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章