4

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..

dave21
  • 315
  • 1
  • 6
  • 14

3 Answers3

16
    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

JesperB
  • 4,625
  • 1
  • 36
  • 40
1

I have this array

{
"result": "success",
"countryCodeList":
[
  {"countryCode":"00","countryName":"World Wide"},
  {"countryCode":"kr","countryName":"Korea"}
] 
}

Here below I am fetching country details, so I have used valArray.getJSONArray(1)

You can use valArray.getJSONArray(0)

JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);

JSONArray valArray1 = valArray.getJSONArray(1);

valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");

int len = valArray1.length();

for (int i = 0; i < valArray1.length(); i++) {

 Country country = new Country();
 JSONObject arr = valArray1.getJSONObject(i);
 country.setCountryCode(arr.getString("countryCode"));                        
 country.setCountryName(arr.getString("countryName"));
 arrCountries.add(country);
}
Nirali
  • 13,571
  • 6
  • 40
  • 53
0

you can use GSON for doing this parsing. it will make your life simple.

you can have a look at my answers in this SO question

Community
  • 1
  • 1
sunil
  • 6,444
  • 1
  • 32
  • 44