如何解决在 Android 中重新字符串化字符串
我有一个字符串,我想在 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 中对字符串进行字符串化?
解决方法
最终使用 JSONArray
类并移除数组包装以欺骗该类将普通字符串字符串化
fun jsonStringifyString(str: String): String {
val jsonStr = JSONArray().put(str).toString()
return jsonStr.substring(1,jsonStr.length - 1) // remove first and last char
}
val serializedData = jsonStringifyString("test=\"123\"");
webview.evaluateJavascript("window.onData(${serializedData})")
// rendered JS: window.onData("test=\"123\"")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。