How to force JSON-lib's JSONObject.put(..) to escape a string containing JSON? How to force JSON-lib's JSONObject.put(..) to escape a string containing JSON? json json

How to force JSON-lib's JSONObject.put(..) to escape a string containing JSON?


This worked for me with json-lib 2.4:

System.out.println(    new JSONStringer()        .object()            .key("jsonStringValue")                .value("{\"hello\":\"world\"}")            .key("naturalStringValue")                .value("\"hello world\"")        .endObject()    .toString());

The output is:

{"jsonStringValue":"{\"hello\":\"world\"}","naturalStringValue":"\"hello world\""}

Is that a possible solution for you?

UPDATE:

Revised my answer with a possible solution


Use single quotes to quote the string. From the documentation:

Strings may be quoted with ' (single quote).

Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.

So modifying your example:

net.sf.json.JSONObject obj = new net.sf.json.JSONObject();obj.put("jsonStringValue","{\"hello\":\"world\"}");obj.put("quotedJsonStringValue","\'{\"hello\":\"world\"}\'");obj.put("naturalStringValue", "\"hello world\"");System.out.println(obj.toString());System.out.println(obj.getString("jsonStringValue"));System.out.println(obj.getString("quotedJsonStringValue"));System.out.println(obj.getString("naturalStringValue"));

Produces:

{"jsonStringValue":{"hello":"world"},"quotedJsonStringValue":"{\"hello\":\"world\"}","naturalStringValue":"\"hello world\""}{"hello":"world"}{"hello":"world"}"hello world"

Note how quotedJsonStringValue has been treated as a string value and not JSON, and appears quoted in the output JSON.