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

1
  • google it out for parsing json Commented Jun 29, 2012 at 11:10

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.