Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to force JSON-lib's JSONObject.put(..) to escape a string containing JSON?
    text
    copied!<p><strong>When using JSON-lib's <code>JSONObject</code>, how can I stop the <code>put</code> method from storing a String which contains JSON as JSON rather than as an escaped string?</strong></p> <p>For instance:</p> <pre><code>JSONObject obj = new JSONObject(); obj.put("jsonStringValue","{\"hello\":\"world\"}"); obj.put("naturalStringValue", "\"hello world\""); System.out.println(obj.toString()); System.out.println(obj.getString("jsonStringValue")); System.out.println(obj.getString("naturalStringValue")); </code></pre> <p>prints:</p> <pre><code>{"jsonStringValue":{"hello":"world"},"naturalStringValue":"\"hello world\""} {"hello":"world"} "hello world" </code></pre> <p>and I want it to print:</p> <pre><code>{"jsonStringValue":"{\"hello\":\"world\"}","naturalStringValue":"\"hello world\""} {"hello":"world"} "hello world" </code></pre> <p>Yes, I realize this is obnoxious. However, this is in support of a JSON serialization pipeline for which, for interoperability's sake, this is the expected behavior. There are cases in which we would be serializing user input which may be/contain valid JSON. We wouldn't want the user input to become a part of the JSON object that we're serializing said input to.</p> <p>Manual escaping doesn't work because it causes JSON-lib to escape the <code>\</code> characters:</p> <pre><code>JSONObject obj = new JSONObject(); obj.put("naturalJSONValue","{\"hello\":\"world\"}"); obj.put("escapedJSONValue", "{\\\"hello\\\":\\\"world\\\"}"); System.out.println(obj.toString()); System.out.println(obj.getString("naturalJSONValue")); System.out.println(obj.getString("escapedJSONValue")); </code></pre> <p>Output:</p> <pre><code>{"naturalJSONValue":{"hello":"world"},"escapedJSONValue":"{\\\"hello\\\":\\\"world\\\"}"} {"hello":"world"} {\"hello\":\"world\"} </code></pre> <p>At this point, any workarounds to enable manual selective escaping of a complex JSON object would completely negate the value of using JSON-lib in the first place.</p> <p>Also, I understand that this question has been asked <a href="https://stackoverflow.com/questions/4547143/json-lib-escaping-preserving-strings">before</a>, but unfortunately I cannot accept its answer so easily. JSON-lib is a heavily-used dependency in many areas of my project and swapping it out would be a big undertaking. I need to be absolutely sure that there's no way to achieve this goal with JSON-lib before I can entertain a swap to Jackson, simple-json, or Gson.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload