Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate JSON Stringer in Android for this format

Tags:

java

json

android

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)

like image 576
Adrian Avatar asked Oct 31 '25 22:10

Adrian


2 Answers

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

like image 170
Sreehari Avatar answered Nov 02 '25 13:11

Sreehari


Try this

  try {
        JSONObject object=new JSONObject();
        object.put("param1","value1");
        object.put("param2","value2");
        JSONObject param3=new JSONObject();
        paraam3.put("username","admin");
        paraam3.put("password","123");
        object.put("param3",param3);
    } catch (JSONException e) {
        e.printStackTrace();
    }
like image 44
Dixit Panchal Avatar answered Nov 02 '25 12:11

Dixit Panchal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!