I have to create json string like below,
{ "data": { "data": "message" }, "status": "SUCCESS" }
I am using below code to create json string on the fly,
> JSONObject jsonObject = new JSONObject();
> JSONObject jsonData = new JSONObject();
> try {
> jsonData.put("data", "message");
> jsonObject.put("data",jsonData);
> jsonObject.put("status", "SUCCESS");
> Log.d("AYadav", new Gson().toJson(jsonObject));
> } catch (JSONException e) {
> e.printStackTrace();
> }
but from above code I am getting below json string,
{ "nameValuePairs": { "data": { "nameValuePairs": { "data": "message" } }, "status": "SUCCESS" } }
Why extra nameValuePairs is coming?
You are mixing two JSON libraries, Gson and (I assume) JSON-java. JSONObject
(with "JSON" completely uppercase) is not part of Gson, it belongs to JSON-java.
If you want to use Gson, then use its class com.google.gson.JsonObject
and then at the end call Gson.toJson
. Do not call JsonObject.toString()
because its documentation currently makes no guarantees that the output will be the JSON document.
If you want to use JSON-java, then keep using the JSONObject
class, but at the end call JSONObject.toString()
.