JSON Array iteration in Android/Java

后端 未结 8 989
广开言路
广开言路 2020-11-22 13:22

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows

8条回答
  •  -上瘾入骨i
    2020-11-22 13:51

    If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:

    @Override
    public Iterator iterator() {
        return this.myArrayList.iterator();
    }
    

    This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.

提交回复
热议问题