如何访问 JSONArray 中的每个键和值

How can I access each key and value in JSONArray

我有一个 JSONArray,如下所示。如何按顺序访问其中的每个键和值。

JSONArray = [{"a":1},{"b":2,"c":3},{"d":4},{"e":5,"f":7}]

您可以试试下面的代码:

JSONArray jsonArray = new JSONArray("[{\"a\":1},{\"b\":2,\"c\":3},{\"d\":4},{\"e\":5,\"f\":7}]");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject json = jsonArray.getJSONObject(i);
    Iterator<String> keys = json.keys();

    while (keys.hasNext()) {
        String key = keys.next();
        System.out.println("Key :" + key + "  Value :" + json.get(key));
    }

}
try below code for nested Json .     
 main method here {
     String res = "" ;// your json here 
      ObjectMapper o = new ObjectMapper();
           Object m = o.readValue(res, Object.class);
           printKeys(m);

    }

    public void printKeys(Object obey)
          {

              if ( obey instanceof ArrayList)
              {
                  @SuppressWarnings("unchecked")
                List<Object> list = (List<Object>)obey;
                  for( Object ob : list )
                  {
                     printKeys(ob);
                  }

              }
              else if ( obey instanceof Map)
              {
                 Map<String, Object> m1 = (Map<String,Object>)obey;
                 for ( String key : m1.keySet() ){
                     System.out.println("KEY :"+ key);
                     printKeys(m1.get(key));
              }
          }

          }