Reputation: 105
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\"}"}
Upvotes: 2
Views: 472
Reputation: 30934
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();
Upvotes: 3
Reputation: 3390
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"}}
Upvotes: 1