Maybe this will help:

JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();

while(keys.hasNext()) {
    String key = keys.next();
    if (jsonObject.get(key) instanceof JSONObject) {
          // do something with jsonObject here      
    }
}
Answer from Rickey on Stack Overflow
🌐
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 start with the simple case of iterating a JSON of name-value pairs: { "name": "Cake", "cakeId": "0001", "cakeShape": "Heart" } For this, we can simply iterate through the keys using the keys() method: void handleJSONObject(JSONObject ...
Discussions

java - Foreach with JSONArray and JSONObject - Stack Overflow
Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this: More on stackoverflow.com
🌐 stackoverflow.com
java - Iterate through JSONObject from root in json simple - Stack Overflow
I am trying to iterate over a json object using json simple. More on stackoverflow.com
🌐 stackoverflow.com
November 17, 2019
java - how to iterate through this json object and format it - Stack Overflow
I've never used Java before so I'm not sure where to begin in creating this script. Mainly I'm concerned with how I will iterate through the json object. More on stackoverflow.com
🌐 stackoverflow.com
java - JSON - Iterate through JSONArray - Stack Overflow
I have a JSON file with some arrays in it. I want to iterate through the file arrays and get their elements and their values. This is how my file looks like: { "JObjects": { "JAr... More on stackoverflow.com
🌐 stackoverflow.com
🌐
JanBask Training
janbasktraining.com › community › java › how-can-i-iterate-json-objects-in-java-programming-language
How can I iterate JSON objects in Java programming language? | JanBask Training Community
January 24, 2024 - This above coding would use the Jackson library for parsing JSON string and then after it would help in iterating through the fields of the JSON object. You can also customize the logic within the loop to suit your particular needs and requirements like as extraction of the values and performing certain actions based on the conditions.
🌐
CodeSpeedy
codespeedy.com › home › how to iterate or loop through json array in java
How to iterate or loop through JSON array in Java - CodeSpeedy
March 7, 2022 - import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class IterateJsonExample { public static void main(String[] args) { JSONParser jsonParserObj = new JSONParser(); try { JSONObject jsonObj = (JSONObject) jsonParserObj.parse(new FileReader("E://Detail.json")); System.out.println("Names are : "); JSONArray jsonArrObj = (JSONArray) jsonObj.get("Names"); Iterator<Strin
🌐
Webkul
webkul.com › home › how to iterate through jsonobject in java and kotlin
How to Iterate through JSONObject in Java and Kotlin - Webkul Blog
January 16, 2026 - Always use opt() methods instead of get() for safer JSON access in both languages. Validate JSON structure before iteration to prevent runtime exceptions and crashes. Consider using modern libraries like Moshi (Kotlin) or Jackson (Java) for complex JSON structures.
🌐
Blogger
javarevisited.blogspot.com › 2022 › 12 › how-to-iterate-over-jsonobject-in-java.html
How to iterate over JSONObject in Java to print all key values? Example Tutorial
May 21, 2023 - Hello guys, if you are wondering how to iterate over a JSONObject in Java and print all its fields and values then you have come to the right place. In this article, I will show you how you can print all data from JSONObject in Java. If you know, In json-simple library, one of the top 5 and lightweight JSON library, JSON object is a wrapper class which contains the actual JSON message.
🌐
Rip Tutorial
riptutorial.com › json iteration
Java Language Tutorial => JSON Iteration
JSONArray arr = new JSONArray(); ... in: arr.put("Stack"); arr.put("Over"); arr.put("Flow"); for (int i = 0; i < arr.length(); i++) {//iterate over all values Object value = arr.get(i); //get value System.out.println(value); //print each value }...
Find elsewhere
🌐
Edureka Community
edureka.co › home › community › categories › java › iterate over a jsonobject
Iterate over a JSONObject | Edureka Community
June 27, 2018 - JSON library called JSONObject is used(I don't mind switching if I need to) We know how to iterate over ... http://url3.com//", "shares": 15 } }
🌐
Codemia
codemia.io › home › knowledge hub › how to iterate over a jsonobject?
How to iterate over a JSONObject? | Codemia
January 26, 2025 - Each key is unique and associated with a single value, which can be a string, number, boolean, array, another JSON object, or null. Let's explore how to iterate over a JSONObject, focusing on its implementation in Java using the popular JSON parsing library org.json.
🌐
Example Code
example-code.com › java › json_array_iterate.asp
Iterate over JSON Array containing JSON Objects | Chilkat Examples
import com.chilkatsoft.*; public class ChilkatExample { static { try { System.loadLibrary("chilkat"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load.\n" + e); System.exit(1); } } public static void main(String argv[]) { boolean success = false; // Loads the following JSON array and iterates over the objects: // // [ // {"tagId":95,"tagDescription":"hola 1","isPublic":true}, // {"tagId":98,"tagDescription":"hola 1","isPublic":true}, // {"tagId":101,"tagDescription":"hola 1","isPublic":true}, // {"tagId":104,"tagDescription":"hola 1","isPublic":true}, /
🌐
iCert Global
icertglobal.com › home › community › what is the best way to iterate through all keys and values in a jsonobject using java?
What is the best way to iterate through all keys and values in a JSONObject using Java? | iCertGlobal Community
April 13, 2024 - If you suspect your JSON is nested, you definitely should use a recursive method. Inside your loop, you can check if the value is an instanceof JSONObject. If it is, simply call your iteration function again on that sub-object.
🌐
Quora
quora.com › How-do-I-iterate-through-JSON-array-object
How to iterate through JSON array object - Quora
Answer (1 of 2): I have the below code which is currently giving me one result. I would like to iterate through the “comments” so that end result will returns all the comments. for each(comments in r.orderLines){ // get Collection comments webservice = webServiceFactory.createWebService('
🌐
GitHub
gist.github.com › 3716977
Iterate through JSONObject and store totals for various terms in hash map. Then construct new JSONObject. · GitHub
Iterate through JSONObject and store totals for various terms in hash map. Then construct new JSONObject. - json_iteration.java
Top answer
1 of 1
1

I would Approach this this way:

  1. Create a main class that holds all the information of the JSON and a Secondary class that keeps the information of the prop properties of the JSON:
public class MainJsonObject
{
    private int $id;
    private int $schema;
    
    // All the other objects that you find relevant...
    
    private List<SecondaryJsonObject> propsList = new ArrayList<>(); // This will keep all your other props with description and type
    
    // Getter and setter, do not forget them as they are needed by the JSON library!!

}

public class SecondaryJsonObject
{
    private String description;
    private String type;
    
    // Getter and setter, do not forget them !!
}
  1. You could iterate through your JSON Object this way:

First of all include the JSON Library in your project.

Then iterate through your JSON like this:

JSONObject jsonObject = new JSONObject(jsonString);

MainJsonObject mjo = new MainJsonObject();
mjo.set$id(jsonObject.getInt("$id")); // Do this for all other "normal" attributes

// Then we start with your properties array and iterate through it this way:

JSONArray jsonArrayWithProps = jsonObject.getJSONArray("properties");

for(int i = 0 ; i < jsonArrayWithProps.length(); i++)
{
    JSONObject propJsonObject = jsonArrayWithProps.getJSONObject(i); // We get the prop object 

    SecondaryJsonObject sjo = new SecondaryJsonObject();
    sjo.setDescription(propJsonObject.getString("description"));
    sjo.setTyoe(propJsonObject.getString("type"));
    
    mjo.getPropsList().add(sjo); // We fill our main object's list.

}
Top answer
1 of 6
102

Change

JSONObject objects = getArray.getJSONArray(i);

to

JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.


I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
    {
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
      {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
      }
      System.out.println();
    }
  }
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/
2 of 6
23
for (int i = 0; i < getArray.length(); i++) {
            JSONObject objects = getArray.getJSONObject(i);
            Iterator key = objects.keys();
            while (key.hasNext()) {
                String k = key.next().toString();
                System.out.println("Key : " + k + ", value : "
                        + objects.getString(k));
            }
            // System.out.println(objects.toString());
            System.out.println("-----------");

        }

Hope this helps someone

🌐
XDA Forums
xdaforums.com › home › general development › app development forums › coding discussion, q&a, and educational resources › java for android app development
How can I loop through my JSON object? | XDA Forums
March 8, 2015 - for(int i = 0; i<json.names().length(); i++){ try { Log.v("TEST", "key = " + json.names().getString(i) + " value = " + json.get(json.names().getString(i))); } catch (JSONException e) { e.printStackTrace(); } } But this will only target "message" which includes the whole JSON "string". I want to loop through each message and retrieving the value of uid 1, uid 2 etc.
🌐
Reddit
reddit.com › r/javahelp › iterate through json objects rather than deserialize all that one.
r/javahelp on Reddit: Iterate through JSON objects rather than deserialize all that one.
April 17, 2023 -

I have a JSON response that will be set up like this:

JSON:

{
  "lines": [
    {
      "currencyTypeName": "Mirror of Kalandra",
      "pay": {
        "id": 0,
        "league_id": 1,
        "pay_currency_id": 22,
        "get_currency_id": 1,
        "sample_time_utc": "2023-04-16T00:34:10.2107897Z",
        "count": 106,
        "value": 0.00000910000000,
        "data_point_count": 1,
        "includes_secondary": true,
        "listing_count": 1155
      },
      "receive": {
        "id": 0,
        "league_id": 1,
        "pay_currency_id": 1,
        "get_currency_id": 22,
        "sample_time_utc": "2023-04-16T00:34:10.2107897Z",
        "count": 44,
        "value": 122100.00000000000000,
        "data_point_count": 1,
        "includes_secondary": true,
        "listing_count": 190
      },
      "paySparkLine": {
        "data": [
          0,
          0,
          0,
          0,
          0,
          0,
          9.89
        ],
        "totalChange": 9.89
      },
      "receiveSparkLine": {
        "data": [
          0,
          -3.05,
          -3.98,
          -4.40,
          -6.81,
          -7.61,
          -8.85
        ],
        "totalChange": -8.85
      },
      "chaosEquivalent": 113471.68,
      "lowConfidencePaySparkLine": {
        "data": [
          0,
          0,
          0,
          0,
          0,
          0,
          9.89
        ],
        "totalChange": 9.89
      },
      "lowConfidenceReceiveSparkLine": {
        "data": [
          0,
          -3.05,
          -3.98,
          -4.40,
          -6.81,
          -7.61,
          -8.85
        ],
        "totalChange": -8.85
      },
      "detailsId": "mirror-of-kalandra"
    },
    {
      "currencyTypeName": "Mirror Shard",
      "pay": {
        "id": 0,
        "league_id": 1,
        "pay_currency_id": 81,
        "get_currency_id": 1,
        "sample_time_utc": "2023-04-16T00:34:10.2107897Z",
        "count": 22,
        "value": 0.00018520000000,
        "data_point_count": 1,
        "includes_secondary": true,
        "listing_count": 50
      },
      "receive": {
        "id": 0,
        "league_id": 1,
        "pay_currency_id": 1,
        "get_currency_id": 81,
        "sample_time_utc": "2023-04-16T00:34:10.2107897Z",
        "count": 37,
        "value": 6398.04000000000000,
        "data_point_count": 1,
        "includes_secondary": true,
        "listing_count": 273
      },
      "paySparkLine": {
        "data": [
          0,
          0,
          0,
          0,
          0,
          0,
          2.59
        ],
        "totalChange": 2.59
      },
      "receiveSparkLine": {
        "data": [
          0,
          -1.79,
          -2.13,
          -2.55,
          -4.26,
          -4.52,
          -6.12
        ],
        "totalChange": -6.12
      },
      "chaosEquivalent": 6025.73,
      "lowConfidencePaySparkLine": {
        "data": [
          0,
          0,
          0,
          0,
          0,
          0,
          2.59
        ],
        "totalChange": 2.59
      },
      "lowConfidenceReceiveSparkLine": {
        "data": [
          0,
          -1.79,
          -2.13,
          -2.55,
          -4.26,
          -4.52,
          -6.12
        ],
        "totalChange": -6.12
      },
      "detailsId": "mirror-shard"
    }
  ]
}

Using Gson, I am parsing the JSON response from a server into a POJO using the below method:

POJO:

public class Currency {

    @SerializedName("chaosEquivalent")
    private Double chaosEquivalent;

    @SerializedName("currencyTypeName")
    private String currencyName;

    @SerializedName("detailsId")
    private String detailsId;

//Getters and setters
}

Gson code:

public List<Currency> getCurrency ( String league, String localization, boolean update ) throws IOException {
        if ( currency == null || update) {
            String url = "https://poe.ninja/api/data/currencyoverview?league=" + league + "&type=Currency" + "&language=" + localization;
            currency = new ArrayList<> (  );

            Gson gson = new Gson ();

            InputStreamReader in = new InputStreamReader ( new URL ( url ).openStream () );
            JsonReader reader = new JsonReader ( in );

            reader.beginObject ();
            reader.nextName ();
            currency = gson.fromJson ( reader, new TypeToken<List<Currency>> () {}.getType () );

            reader.close ();
        }

        return currency;
    }

The issue:

The above Gson code works if I want to parse the entirety of the JSON response. Instead of the entirety of the response, I only want to parse what I need to via stream until I identify the item I'm looking for.

For example:

while ( reader.hasNext () ) {

            /*
             * What do I need to do before this line?
             */
            Currency c = gson.fromJson ( reader, Currency.class );
            
            if ( c.name().equals ( "nameofobjectlookingfor" ) ) {
                //Do stuff that I need to do.
            }
        }

However, I seem to not be able to do the above in one way or another. I always get errors stating BEGIN_ARRAY expected but was STRING, or BEGIN_OBJECT. I still want to map the JSON to the POJO, but I am struggling to find the solution. Essentially, I want to map objects one at a time instead of bulk.

Is this a possibility? Examples online show utilizing the peek() method and comparing tokens, but that seems to send me down the road of manually mapping every object through if statements when I believe I should be able to just map via the Gson class.