Android 2.3.7 Webview不接受字符串化的json(结果总是一个空对象)

时间:2015-05-28 20:45:11

标签: javascript android json webview

没有例外,没有。尝试通过webview中的javascript界面​​将返回的字符串化JSON解析为对象,但仅在Android 2.3.7 webview中不起作用。

返回的字符串很简单:“{test:true}”。我使用了两种方法:

oResult = window.app.getDemoObj(); // This function is a java function and resturns the string

alert( typeof oResult ); // Shows that is it a string
    alert( oResult ); // shows the content
    if( typeof oResult === 'string' )
     { 
       // Tried both methods but result is always odd object            
       if( window.JSON )
        { oResult = JSON.parse(oResult); }
       else 
        { oResult = (new Function('return '+(new String(oResult))+';'))(); }
       alert( oResult.test ); // shows undefined, the object is empty with both methods
     }

当我用window.app.getDemoObj()替换行"{test:true}"时,两种方法都能完美无瑕。它似乎是一个安全/起源问题/设置?

如何让它像其他Android版本一样工作?

1 个答案:

答案 0 :(得分:0)

我认为你可能遇到的是你需要字符串化而不是解析JSON。

要将JSON对象转换为文本,请使用JSON.stringify

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

要将文本转换为JSON对象,请使用JSON.parse

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse