Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access each key and value in JSONArray

I have a JSONArray as below. How can I access each key and value in it in order.

JSONArray = [{"a":1},{"b":2,"c":3},{"d":4},{"e":5,"f":7}]
like image 365
user3712016 Avatar asked Dec 11 '22 23:12

user3712016


1 Answers

You can try following code:

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

}
like image 166
Sachin Gupta Avatar answered Dec 28 '22 07:12

Sachin Gupta