【发布时间】:2021-07-15 15:04:18
【问题描述】:
我有一个字符串,我想在 Kotlin (Android) 中进行字符串化,但似乎 org.json.* 不支持获取字符串并重新对其进行字符串化,而是总是尝试先解析它。
val str = "test=\"123\""
val stringified = JSONObject(str).toString() // JSONException: Value a of type java.lang.String cannot be converted to `JSONObject`
此功能的用例是以安全的方式将数据传递给 Webview 中的 JS。
val json = "test=\"123\""
webview.evaluateJavascript("window.onData(${json})")
// on the JS side it will look like this: window.onData(test="123")
// this is both invalid and insecure since it opens the door for raw JS injection
任何手动操作都会导致不安全且可能无效的 JS 字符串
这个例子应该不被使用:val insecureJSON = "'${str.replace("\\", "\\\\").replace("\"", "\\\"").replace("'", "\'")}'"
期望的行为:
val json = jsonStringifyString("test=\"123\"")
webview.evaluateJavascript("window.onData(${json})")
// rendered JS: window.onData("test=\"123\"")
有没有简单的方法在 Android 中对字符串进行字符串化?
【问题讨论】:
标签: java android json kotlin stringify