Java – How to generate a JSON Stringer for this format in Android

How to generate a JSON Stringer for this format in Android… here is a solution to the problem.

How to generate a JSON Stringer for this format in Android

I need to send data to the database in this format –

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

How to generate this using JSONStringer?

I tried-

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 got this error –

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

Solution

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, you can apply the reverse of JSON parsing to create a JSON string object in order to send it to the server/database

Related Problems and Solutions