Now that we can see the data, we can see that payments is in fact an array (values uses []).

That means you need to call rootObj.getAsJsonArray("payments") which returns a JsonArray, and it is an Iterable<JsonElement>, which means your loop should be for(JsonElement pa : paymentsObject).

Remember, each value of the array can be any type of Json element (object, array, string, number, ...).

You know that they are JsonObject, so you can call getAsJsonObject() on them.

json = (json data)
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray paymentsArray = rootObj.getAsJsonArray("payments");
for (JsonElement pa : paymentsArray) {
    JsonObject paymentObj = pa.getAsJsonObject();
    String     quoteid     = paymentObj.get("quoteid").getAsString();
    String     dateEntered = paymentObj.get("date_entered").getAsString();
    BigDecimal amount      = paymentObj.get("amount").getAsBigDecimal();
}
Answer from Andreas on Stack Overflow
🌐
Java Tips
javatips.net › api › com.google.gson.jsonarray
Java Examples for com.google.gson.JsonArray - Javatips.net
@Override public List<TermsOfUse> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // Get the json element as array JsonArray array = json.getAsJsonObject().get(TermsOfUse.KEY_TERMSOFUSE).getAsJsonArray(); // Iterate over each json object List<TermsOfUse> res = new ArrayList<>(array.size()); for (int i = 0, size = array.size(); i < size; i++) { // and deserialize the json object. res.add(context.deserialize(array.get(i), TermsOfUse.class)); } return res; } ... @Override public void setResponseObject(CommonResponseBody<T> responseBody,
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.iterator java code examples | Tabnine
private List<String> getLocatorsFromJSONBody(String tenantId, String body) { JsonElement element = gson.fromJson(body, JsonElement.class); JsonArray metrics = element.getAsJsonArray(); final List<String> locators = new ArrayList<String>(); Iterator<JsonElement> it = metrics.iterator(); while (it.hasNext()) { JsonElement metricElement = it.next(); locators.add( metricElement.getAsString()); } return locators; }
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › 2.6.2 › com › google › gson › JsonArray.html
JsonArray - gson 2.6.2 javadoc
Bookmarks · Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.6.2 · https://javadoc.io/doc/com.google.code.gson/gson/2.6.2 · package-list path (used for javadoc generation -link option) · https://javadoc.io/doc/com.goog...
Top answer
1 of 4
3

So you have the JsonArray object with your records, here's what you do to get your functional objects:

Type type = new TypeToken<List<DataMetrics>>() {}.getType();
List<DataMetrics> records = gson.fromJson(jsonArrayThatYouHave, type);

Then you iterate through you objects and filter the ones you need. In java 8 you can do this:

List<DataMetrics> result = records.stream().filter(record -> record.name.equals("Client::Sync")).collect(toList());

This approach is converting all objects and iterating after, if exactly this part of code is performance critical, you can still iterate through json and convert only necessary objects (but i doubt that this will be actually faster than described above).

Anyway this is more maintainable and understandable code.

UPDATE:

the same for java 7 will be:

List<DataMetrics> result = new LinkedList<>();

for(DataMetrics record : records){
   if(record.name.equals("Client::Sync")){
      result.add(record);
   }
}
2 of 4
1

Or if you want to iterate json and parse only required ones heres what you can do:

Type type = new TypeToken<List<DataMetrics>>() {}.getType();

for(JsonElement elem : jsonArrayThatYouHave) {
   if (elem.getAsJsonObject().get("name").getAsString().equals("Client::Sync")) {
      result.add(gson.fromJson(elem, type));
   }
}

but I dont think this is actually faster than the first one because in both cases you are converting json to java functional object with parser and getting JsonArray or anything else. Taking into consideration the fact that both are Googles libs, i assume that parsing from JsonObject to some specific type with gson is way faster than from String (raw json) to the same specific type...

🌐
Java2s
java2s.com › example › java-api › com › google › gson › jsonarray › iterator-0-1.html
Example usage for com.google.gson JsonArray iterator
public ArrayList<ProductosFactEntitiy> generaListaProductos() { JsonElement json = new JsonParser().parse(this.productosArray); JsonArray array = json.getAsJsonArray(); Iterator iterator = array.iterator(); ArrayList<ProductosFactEntitiy> productosList = null; while (iterator.hasNext()) { if (productosList == null) { productosList = new ArrayList<>(); }/* w w w .j a va 2s. c o m*/ JsonElement json2 = (JsonElement) iterator.next(); Gson gson = new Gson(); ProductosFactEntitiy prod = gson.fromJson(json2, ProductosFactEntitiy.class); productosList.add(prod); } return productosList; }
🌐
Medium
medium.com › @reham.muzzamil_67114 › a-quick-guide-to-iterate-over-a-dynamic-json-string-6b024aa6b1e
A quick guide to Iterate over a dynamic JSON string! | by Reham Muzzamil | Medium
May 16, 2020 - Following snippet traverses JsonElement using the Gson library. We have to convert JSON string into JsonElement first before traversal! JsonElement is a class that represents JSON. JsonElement could either be a JsonPrimitive, a JsonArray, a JsonObject, or a JsonNull.
Find elsewhere
🌐
Codota
codota.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.iterator java code examples | Codota
@Override public List<PortConfig> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return new ArrayList<PortConfig>(); } List<PortConfig> pcs = new ArrayList<PortConfig>(); JsonArray array = json.getAsJsonArray(); Iterator<JsonElement> it = array.iterator(); while (it.hasNext()) { JsonElement element = it.next(); pcs.add(s_gson.fromJson(element, PortConfig.class)); } return pcs; } }
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Converting JSON Array to Java List with Gson - Java Code Geeks
April 25, 2024 - We parse a JSON array into a JsonArray using Gson’s JsonParser. Then, we iterate over each element of the array, converting them into Java objects using Gson’s fromJson() method. Finally, we add each Java object to a List.
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.forEach java code examples | Tabnine
filters.getAsJsonArray().forEach((f) -> viewFilters.add(context.deserialize(f, DashboardFilter.class)));
🌐
Baeldung
baeldung.com › home › json › iterating over an instance of org.json.jsonobject
Iterating Over an Instance of org.json.JSONObject | Baeldung
May 5, 2025 - Let’s try and keep a similar approach of using an iterator. Instead of calling keys(), though, we’ll call iterator(): void handleJSONArray(JSONArray jsonArray) { jsonArray.iterator().forEachRemaining(element -> { handleValue(element) }); }
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson – parse json array to java array or list
Gson - Parse JSON Array to Java Array or List
April 4, 2023 - String userJson = "[{'name': 'Alex','id': 1}, " + "{'name': 'Brian','id':2}, " + "{'name': 'Charles','id': 3}]"; Gson gson = new Gson(); Type userListType = new TypeToken<ArrayList<User>>(){}.getType(); ArrayList<User> userArray = gson.fromJson(userJson, userListType); for(User user : userArray) { System.out.println(user); }
🌐
YouTube
youtube.com › hey delphi
Array : How to iterate JSON Array and extract each JSON Object from it using GSON? - YouTube
Array : How to iterate JSON Array and extract each JSON Object from it using GSON?To Access My Live Chat Page, On Google, Search for "hows tech developer con...
Published   April 13, 2023
Views   4
🌐
GitHub
github.com › google › gson › blob › main › gson › src › main › java › com › google › gson › JsonArray.java
gson/gson/src/main/java/com/google/gson/JsonArray.java at main · google/gson
import com.google.gson.internal.NonNullElementWrapperList; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Iterator; import java.util.List; · /** * A class representing an array type in JSON. An array is a list of {@link JsonElement}s each of ·
Author   google
🌐
Mkyong
mkyong.com › home › java › how to parse json array using gson
How to parse JSON Array using Gson - Mkyong.com
May 17, 2024 - package com.mkyong.json.gson; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mkyong.json.gson.model.Item; import java.lang.reflect.Type; import java.util.List; public class GsonParseJsonArrayExample1 { public static void main(String[] args) { String json = """ [ { "id": 1, "name": "a" }, { "id": 2, "name": "b" } ] """; Gson gson = new Gson(); // create a List<Item> Type listItemType = new TypeToken<List<Item>>() {}.getType(); // convert json array to List<Item> List<Item> list = gson.fromJson(json, listItemType); list.forEach(System.out::println); } }
🌐
Bg
jgrass.fon.bg.ac.rs › example-of-iterating-through-json-attributes-in-gson
Example of iterating through JSON attributes in Gson – Advanced Java Programming Tools and Techniques
August 5, 2018 - In each iteration, entry references an object being accessed in the current iteration. In our example, by using the getKey() method we can fetch the JSON attribute name (country code), and by invoking the getValue() method we can fetch the value of the JSON attribute.
🌐
Learn IT University
learn-it-university.com › home › how to iterate over a json array using gson
How to Iterate Over a JSON Array Using Gson - Learn IT University
July 8, 2024 - This method call returns an Iterable<JsonElement>, allowing you to iterate through each element of the JSON array. You can then loop through the elements using a for loop as shown below: JsonParser parser = new JsonParser(); JsonObject rootObj ...
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › latest › com.google.gson › com › google › gson › JsonArray.html
JsonArray - gson 2.13.2 javadoc
Bookmarks · Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.13.2 · https://javadoc.io/doc/com.google.code.gson/gson/2.13.2 · package-list path (used for javadoc generation -link option) · https://javadoc.io/doc/com.go...