Skip to content

Gson – Loop & Iterate JSON Array

Gson – Loop & iterate JSON Array example shows how to loop JSON array using the Gson library in Java. The example also shows how to iterate over a JSON array using the for loop.

How to iterate JSON array using the for loop?

For this example, I’m going to use the below given Employee JSON data.

The “Experience” property contains an array that has relevant companies as individual array elements. To iterate this array using the for loop, first of all, we need to parse this JSON into JsonObject.

Once we get the JsonObject, we can get the array of JSON objects contained in the array and iterate over it using the for loop as given below.

Output

In the above example, the “Experience” JSON array contained the company JSON objects as its elements. So we used the getAsJsonObject method for each element of an array. We have to use the corresponding methods according to the JSON array element data type.

For example, the “Languages” array contains string values as elements. For these values, we just need to use the getAsString method inside the for loop while iterating as given below.

Output

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.