When using JSON-lib JSONObject , how can I stop the put method from storing a String that contains JSON as JSON and not as an escaped string?
For instance:
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"));
prints:
{"jsonStringValue":{"hello":"world"},"naturalStringValue":"\"hello world\""} {"hello":"world"} "hello world"
and I want it printed:
{"jsonStringValue":"{\"hello\":\"world\"}","naturalStringValue":"\"hello world\""} {"hello":"world"} "hello world"
Yes, I understand that this is unpleasant. However, this does support the JSON serialization pipeline, for which, for interoperability, this is the expected behavior. There are cases when we will serialize user input, which may be / contain valid JSON. We do not want user input to become part of the JSON object that we serialize the specified input.
Manual escaping does not work because JSON-lib avoids the \ characters:
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"));
Conclusion:
{"naturalJSONValue":{"hello":"world"},"escapedJSONValue":"{\\\"hello\\\":\\\"world\\\"}"} {"hello":"world"} {\"hello\":\"world\"}
At this point, any workarounds to enable manual selective escaping of a complex JSON object completely negate the importance of using JSON-lib in the first place.
In addition, I understand that this question has been asked before , but, unfortunately, I cannot easily accept his answer. JSON-lib is a heavily used dependency in many areas of my project, and sharing it will be a big deal. I need to be absolutely sure that there is no way to achieve this goal with JSON-lib before I can entertain the exchange for Jackson, just-json or Gson.