9

I'm curious if there's a syntactic way to extend JSONArray such that I can then use it in a for(:) loop as I can a List.

So, instead of having to do:

for(int i = 0; i< myJsonArray.length(); i++){
    myJsonArray.getString(i);
}

I would like to do

for(String s : myJsonArray);

I realize that I need to make sure that in the above example the object in the array is indeed a String, but given that JSONArrays can only handle a few types that shouldn't be problem.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236

2 Answers2

5

With a slight adjustment to the desired syntax:

for(String s : iterable(myJsonArray))

Then write the iterable method something like so:

public static Iterable<String> iterable(final JSONArray array) {
   return new Iterable<String> {
       Iterator<String> iterator() {
          return new Iterator<String> {
             int i = 0;

             boolean hasNext(){
                return i < array.length();
             }

             String next(){
                return array.getString(i++);
             }

             void remove(){
                throw new RuntimeException(); //implement if you need it
             }
          }
       }
   };
}

I realize that I need to make sure that in the above example the object in the array is indeed a String

Well not really as if it isn't a String, it will be coerced to a String anyway.

weston
  • 54,145
  • 21
  • 145
  • 203
1

This is known as the enhanced for loop. ref

I believe the collection needs to implement Iterable to get that functionality. (or you need an Iterable) This is how you would do it, use enhanced for loop with your class.

JsonArray does not; so no you can't :-)

Blundell
  • 75,855
  • 30
  • 208
  • 233