How to iterate over a JSONObject?

后端 未结 16 1884
孤街浪徒
孤街浪徒 2020-11-22 04:17

I use a JSON library called JSONObject (I don\'t mind switching if I need to).

I know how to iterate over JSONArrays, but when I parse JSO

16条回答
  •  被撕碎了的回忆
    2020-11-22 04:34

    First put this somewhere:

    private  Iterable iteratorToIterable(final Iterator iterator) {
        return new Iterable() {
            @Override
            public Iterator iterator() {
                return iterator;
            }
        };
    }
    

    Or if you have access to Java8, just this:

    private  Iterable iteratorToIterable(Iterator iterator) {
        return () -> iterator;
    }
    

    Then simply iterate over the object's keys and values:

    for (String key : iteratorToIterable(object.keys())) {
        JSONObject entry = object.getJSONObject(key);
        // ...
    

提交回复
热议问题