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

前端 未结 2 916
半阙折子戏
半阙折子戏 2020-12-20 18:38

When using JSON-lib\'s JSONObject, how can I stop the put method from storing a String which contains JSON as JSON rather than as an escape

相关标签:
2条回答
  • 2020-12-20 18:58

    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

    0 讨论(0)
  • 2020-12-20 19:07

    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.

    0 讨论(0)
提交回复
热议问题