getting JSONArray at Index from JSONObject



我有一个JSONObject,里面有多个JSONArray。我已经编写了一个 for 循环来循环对象,但我需要在索引位置获取 JSONArray。有谁知道如何做到这一点?

这是我的 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.. 
      }
} 

这是我的 for 循环,我遇到的问题是要从 JSONObject 中检索 JSONArray,它需要一个字符串,但我正在尝试在 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););   
                    }

试试这个:

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

请注意,定义 JSONObject 元素的顺序

在这里,您将获得匹配的索引。

 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;
                }
            } 

最新更新