场景 Android 本地 需要 传递 jsonObject 参数 给 js ,报 "Uncaught SyntaxError: Unexpected token x",该错误 一般 是 由于 传输 和 接收 参数 时,类型 不统一造成的,
由于 js 是 弱类型,所以Android 端 定义好 参数类型,再传递。
说下 我遇到的问题 ,以及 解决方法
try { JSONArray jsonArray = new JSONArray(); JSONObject tmpObj = null; tmpObj = new JSONObject(); tmpObj.put("count" , unreadMsg.getCount()); tmpObj.put("fromUserId", unreadMsg.getFromUserId()); JSONObject jj = new JSONObject(tmpObj.toString()) ;//将 unreadMsg 对象 转为 json 对象 jsonArray.put(jj);// 将 json对象 添加到 数组, tmpObj = null; jsonObject9.put("command", "CARD_EVENT"); jsonObject9.put("type", "msg_count_init"); jsonObject9.put("value" , jsonArray); // 直接 传递 对象 } catch (JSONException e) { e.printStackTrace(); } mWebView.loadUrl("javascript:CALL_HTML('" + jsonObject9 + "')"); js 端 接受 的数据格式 { "command": "CARD_EVENT", "type": "msg_count_init", "value": [{"count":1,"fromUserId":"777777863"}, {"count":1,"fromUserId":"777777862"}] } 要求 value 里面 数 jsonArray ,jsonArray 里面 是 UnreadMsg 对象 (两个字段 ,int count)String fromUserId
错误 代码 如下JSONObject jsonObject9 = new JSONObject(); try { JSONArray jsonArray = new JSONArray(); JSONObject tmpObj = null; tmpObj = new JSONObject(); tmpObj.put("count" , unreadMsg.getCount()); tmpObj.put("fromUserId", unreadMsg.getFromUserId()); jsonArray.put(tmpObj);// 应为 此时 tmpObj ,添加 到 array里面的 数据 不是 对象,是 字符串 "[{\"count\":1,\"fromUserId\":\"777777863\"}]" tmpObj = null; jsonObject9.put("command", "CARD_EVENT"); jsonObject9.put("type", "msg_count_init"); jsonObject9.put("value" , jsonArray); // } catch (JSONException e) { e.printStackTrace(); } mWebView.loadUrl("javascript:CALL_HTML('" + jsonObject9 + "')"); 这只是 我 遇到的 情况,也可能 有其他情况,遇到该类问题 重点 排查 参数 类型 问题 (记录下来 ,方便 以后 查看)