Android JSONObject - 我如何循环通过一个平面 JSON 对象来获取每个键和值

2022-01-31 00:00:00 json android java
{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

在事先不知道key和value的情况下,如何获取每个item的key和value?

How I can get each item's key and value without knowing the key nor value beforehand?

推荐答案

使用keys() 迭代器遍历所有属性,并调用 get() 为每个.

Use the keys() iterator to iterate over all the properties, and call get() for each.

Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);
    } catch (JSONException e) {
        // Something went wrong!
    }
}

相关文章