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
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.iterator java code examples | Tabnine
private List<String> ... element.getAsJsonArray(); final List<String> locators = new ArrayList<String>(); Iterator<JsonElement> it = metrics.iterator(); while (it.hasNext()) { JsonElement metricElement = it.next(); ...
🌐
Java Tips
javatips.net › api › com.google.gson.jsonarray
Java Examples for com.google.gson.JsonArray - Javatips.net
@Override public List<TermsOfUse> ...onObject().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. ...
🌐
Program Creek
programcreek.com › java-api-examples
com.google.gson.JsonArray#iterator
private static void getSizeMultiDimensionalArray(JsonArray jsonArray, List<Integer> dimensions) { Iterator<JsonElement> iterator = jsonArray.iterator(); if (iterator.hasNext()) { JsonElement jsonElement = iterator.next(); if (jsonElement.isJsonArray()) { JsonArray shapeArray = jsonElement.getAsJsonArray(); dimensions.add(shapeArray.size()); getSizeMultiDimensionalArray(shapeArray, dimensions); } } } ... private static <T> ArrayList<T> JSONArrayStringToArrayList(String jsonString,Class<T> classofT){ Gson gson=new Gson(); JsonParser parser = new JsonParser(); JsonElement el = parser.parse(jsonString); JsonArray jsonArray=el.getAsJsonArray(); Iterator<JsonElement> it = jsonArray.iterator(); ArrayList<T> al=new ArrayList<>(); while(it.hasNext()){ JsonElement e = it.next(); T data=gson.fromJson(e, classofT); al.add(data); } return al; }
🌐
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...
🌐
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); } }
🌐
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; }
Find elsewhere
🌐
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 - } else { return primitive; } } else if (element.isJsonArray()) { JsonArray jsonArray = element.getAsJsonArray(); JsonArray cleanedNewArray = new JsonArray(); for (JsonElement jsonElement : jsonArray) { cleanedNewArray.add(traverse(jsonElement)); } return cleanedNewArray; } else if (element.isJsonNull()) { return element.getAsJsonNull(); } else { JsonObject obj = element.getAsJsonObject(); JsonObject encodedJsonObject = new JsonObject(); for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { encodedJsonObject.add(StringUtils.encodeValue(entry.getKey()), traverse(entry.getValue())); } return encodedJsonObject; } }
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
2

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...

🌐
Codota
codota.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.iterator java code examples | Codota
Iterator<JsonElement> li = array.iterator(); while (li.hasNext()) { JsonElement recordElement = li.next(); ... @Test public void list_of_numbers() { JsonArray objs = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.store.book[*].displ...
🌐
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.
🌐
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 = ...
🌐
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) }); }
Top answer
1 of 5
13

replace "" with blank.

   Map<String, Object> attributes = new HashMap<String, Object>();
   Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
   for(Map.Entry<String,JsonElement> entry : entrySet){
    if (! nonProperties.contains(entry.getKey())) {
      properties.put(entry.getKey(), jsonObject.get(entry.getKey()).replace("\"",""));
    }
   }
2 of 5
5

How are you creating your JsonObject? Your code works for me. Consider this

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
...
...
...
try{
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keyInt", 2);
        jsonObject.addProperty("keyString", "val1");
        jsonObject.addProperty("id", "0123456");

        System.out.println("json >>> "+jsonObject);

        Map<String, Object> attributes = new HashMap<String, Object>();
        Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
        for(Map.Entry<String,JsonElement> entry : entrySet){
          attributes.put(entry.getKey(), jsonObject.get(entry.getKey()));
        }

        for(Map.Entry<String,Object> att : attributes.entrySet()){
            System.out.println("key >>> "+att.getKey());
            System.out.println("val >>> "+att.getValue());
            } 
    }
    catch (Exception ex){
        System.out.println(ex);
    }

And it is working fine. Now I am interested in knowing how you created that JSON of yours?

You can also try this (JSONObject)

import org.json.JSONObject;
...
...
...
try{
        JSONObject jsonObject = new JSONObject("{\"keyInt\":2,\"keyString\":\"val1\",\"id\":\"0123456\"}");
        System.out.println("JSON :: "+jsonObject.toString());

        Iterator<String> it  =  jsonObject.keys();
         while( it.hasNext() ){
             String key = it.next();
             System.out.println("Key:: !!! >>> "+key);
             Object value = jsonObject.get(key);
             System.out.println("Value Type "+value.getClass().getName());
            }
    }
    catch (Exception ex){
        System.out.println(ex);
    }
🌐
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
🌐
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 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. The method getValue() returns a reference of the class JsonElement. As depicted in the presentation (page 16), ...
🌐
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