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

2022-01-10 00:00:00 json iterator java jsonobject

我有一个如下的 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}]

推荐答案

你可以试试下面的代码:

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

}

相关文章