Luke Batley
Luke Batley

Reputation: 2402

getting JSONArray at Index from JSONObject

I have a JSONObject with multiple JSONArrays in it. I have written a for loop to loop through the object but i need to get the JSONArray at the Index position. Does anyone know how to do this?

heres my JSONObject

{"Contacts": //JSONObject
  {
    "B"://JSONArray..
    [
        {"ContactName":sdfsdf,"ID":900,"Number":1368349}, 
        {"ContactName":adsdfd,"ID":1900,"Number":136856},  
         {"ContactName":adglkhdofg,"ID":600,"Number":136845}
   ],
  "C":[
         {"ContactName":alkghoi,"ID":900,"Number":1368349},
         {"ContactName":wetete,"ID":1900,"Number":136856}, 
         {"ContactName":dfhtfh,"ID":600,"Number":136845}
     ]
      .....//and so on.. 
      }
} 

heres my for loop this issue i'm having is that to retrieve a JSONArray from a JSONObject it requires a string but i'm trying to get the Array at object Index in the JSONObject

JSONArray headerStrings = contacts.names();
                    Log.v("Main", "headerStrings = " + headerStrings);

                    SeparatedListAdapter adapter = new SeparatedListAdapter(this);  

                    for (int t=0; t<contacts.length(); t++){

                    adapter.addSection(headerStrings.getString(t), new DocumentArrayAdapter (getActivity(),R.layout.document_cell,contacts.getJSONArray(t););   

                    }

Upvotes: 0

Views: 3417

Answers (2)

Chandan Yadav
Chandan Yadav

Reputation: 144

Here, You will get matched index.

 int matchedIndex =0;
 for(int i=0;i<jsonArray.length();i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if( 123 == jsonObject.getInt("Id")){
                    matchedIndex = i;
                    //jsonArraySelectedBikes.remove(matchedIndex);
                    break;
                }
            } 

Upvotes: 1

Ridcully
Ridcully

Reputation: 23665

Try this:

for (Iterator it = contacts.keys(); it.hasNext(); ) {
    String name = (String)it.next();
    JSONArray arr = contacts.optJSONArray(name);
    // now add this to your adapter
}

Note, that the order of the elements of a JSONObject is not defined.

Upvotes: 4

Related Questions