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.
1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0).
Looping Using JSON JSON stands for JavaScript Object Notation. It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values.
We can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument.
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.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With