Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Json using JsonArray and JsonObject

Tags:

json

android

I want to create a Json structure which is actually a JsonArray inside a JsonObject. The sample structure is:

1.

{
“req”: [
{
  “ctrlId”:”txt1”
},
{
  “ctrlId”:”txt2”
}
]
}

2.

{
“req”: [
{
  “ctrlId”:”txt1”,
  “val” : “val1”
},
{
  “ctrlId”:”txt2”,
  “val” : “val2”
}
]
}

But i am not able to get it..Any help is appreciated..

like image 575
dave21 Avatar asked Dec 04 '22 03:12

dave21


1 Answers

    JSONObject obj = new JSONObject();
    JSONArray req = new JSONArray();

    JSONObject reqObj = new JSONObject()
    reqObj.put( "ctrlId", "txt1" );
    req.put( reqObj );
    reqObj = new JSONObject();
    reqObj.put( "ctrlId", "txt2" );
    req.put( reqObj );

    obj.put( "req", req );

The final object is obj

like image 177
JesperB Avatar answered Dec 09 '22 16:12

JesperB