title: re-stringify a string in Android
body: <p>I have a string that i'd like to stringify in Kotlin (Android), but it seems that <code>org.json.*</code> doesn't support taking a string and re-stringifying it, instead it always tries to parse it first.</p>
  <pre class="lang-kotlin prettyprint-override"><code>val str = &quot;test=\&quot;123\&quot;&quot;
  val stringified = JSONObject(str).toString() // JSONException: Value a of type java.lang.String cannot be converted to `JSONObject`
  </code></pre>
  <p>The use case for this ability is passing data to JS inside a Webview in a secure manner.</p>
  <pre class="lang-kotlin prettyprint-override"><code>val json = &quot;test=\&quot;123\&quot;&quot;
  webview.evaluateJavascript(&quot;window.onData(${json})&quot;)
  // on the JS side it will look like this: window.onData(test=&quot;123&quot;)
  // this is both invalid and insecure since it opens the door for raw JS injection
  </code></pre>
  <p>Any attempt to do it manually will result in an insecure and possibly invalid JS string<br />
  This example should <strong>NOT</strong> be used:<br />
  <code>val insecureJSON = &quot;'${str.replace(&quot;\\&quot;, &quot;\\\\&quot;).replace(&quot;\&quot;&quot;, &quot;\\\&quot;&quot;).replace(&quot;'&quot;, &quot;\'&quot;)}'&quot;</code></p>
  <p>The desired behavior:</p>
  <pre class="lang-kotlin prettyprint-override"><code>val json = jsonStringifyString(&quot;test=\&quot;123\&quot;&quot;)
  webview.evaluateJavascript(&quot;window.onData(${json})&quot;)
  // rendered JS: window.onData(&quot;test=\&quot;123\&quot;&quot;)
  </code></pre>
  <p>Is there an easy method for stringifying a string in Android?</p>