Adrian Adrian - 5 months ago 32
Java Question

How to generate JSON Stringer in Android for this format

I need to send data to database in this format -

{"param1":"value1", "param2":"value2", "param3": {"username": "admin", "password": "123"}}


How to generate this using JSONStringer ?

I tried this -

vm = new JSONStringer().object().key("param1").value("value1")
.object().key("param2").value("value2")
.key("param3").object()
.key("username").value("admin")
.key("password").value("123")
.endObject().endObject().endObject();


But I'm getting this error -


org.json.JSONException: Nesting problem at
org.json.JSONStringer.beforeValue(JSONStringer.java:415)

Answer
JSONObject object1 = new JSONObject();

object1.put("param1", "value1");
object1.put("param2", "param2");

JSONObject innerObject1 = new JSONObject();
innerObject1.put("username", "admin");
innerObject1.put("password", "123");

object1.put("param3",innerObject1);

String jsonStr = object1.toString();

Ideally reverse of JSON parsing can be applied to create a json string object, so that the same can be send to Server/DB

Comments