简体   繁体   中英

Unintended escaping in JSON String

I want to create json string like . .

{"data":"{"name":"jay"}"}

using org.json.* packages . .

or using another packages..

my code is ::

try {       
String strJSONStringer = new JSONStringer().object().key("name").value("jay").endObject().toString();

String record = new JSONStringer().object().key("data") .value(strJSONStringer).endObject().toString();

System.out.println("JSON STRING " + record);

} catch (JSONException e) {
        e.printStackTrace();

System.out.println("### ERROR ###  ::  " + e.getMessage());

}

The program's output:

JSON STRING {"data":"{\"name\":\"jay\"}"}

Your problem is that you do a toString() on the name=jay inner object, which turns this from an object into a string. In the second line you basically then say data=<string from above> so that the Json library has to encode the " in the string by escaping it with \\ .

So you would probably go like this:

JSONObject inner = new JSONObject().put("name","jay");
JSONObject outer = new JSONObject().put("data",inner);

String result = outer.toString();

You shouldn't build your JSON String in two parts, this causes the second JSONStringer to escape your data.

Simply use the builder to build nested objects:

try {
    String record = new JSONStringer()
            .object()
            .key("data")
                .object()
                .key("name").value("jay")
                .endObject()
            .endObject().toString();

    System.out.println("JSON STRING " + record);

} catch (JSONException e) {
    e.printStackTrace();
    System.out.println("### ERROR ### :: " + e.getMessage());
}

This gives me:

JSON STRING {"data":{"name":"jay"}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM