Search code examples
javajsonescapingsanitizationorg.json

Sanitising a JSON String value in Java


I need to accept a string from the user and put it as-is into a JSONObject. The documentation says strings may be quoted with ' but it seems obvious I've misunderstood.

Is this sufficient or am I missing something?

jsonObject.put("name", "'" + userInput + "'");

I stepped through the put function but it doesn't seem to care about the string at all! There's a quote function but it adds another set of double quotes around the string which seems incorrect.


Solution

  • You seem to be quoting this part of the Javadoc

    Strings may be quoted with ' (single quote).

    which is preceded by

    The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:

    JSON strings are wrapped in double quotes ". so JSONObject#toString will produce a JSON value where JSON strings will be syntactically correct. However, the JSONObject constructor can accept a JSON value (as text) where JSON strings are surrounded with single quotes instead of double quotes.

    For example

    JSONObject object = new JSONObject("{'bad':'json'}"); // not valid JSON
    System.out.println(object);
    

    produces the valid

    {"bad":"json"}
    

    The put method is completely unrelated here. You don't need (and shouldn't) use single quotes around your specified string.


    From your comments

    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"