How to create Json using JsonArray and JsonObject

17,767

Solution 1

    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

Solution 2

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);
}
Share:
17,767
dave21
Author by

dave21

Updated on June 13, 2022

Comments

  • dave21
    dave21 about 2 years

    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
    dave21 almost 12 years
    @jesperB...Thanks buddy. Now i got it how to do it.:-)
  • Vipul
    Vipul almost 12 years
    @dave21 If this solved your issue then you should give credit to this person by accepting his answer :)