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 - 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
how to iterate through json objects in java - Stack Overflow
Now you're trying to call iterator() on JSONObject, which doesn't have such a method... ... There's not a JSONArray, only a few JSONObjects. More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 31, 2014
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
java - How can I iterate JSONObject to get individual items - Stack Overflow
This is my below code from which I need to parse the JSONObject to get individual items. This is the first time I am working with JSON. So not sure how to parse JSONObject to get the individual items More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 13, 2012
๐ŸŒ
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 } }
๐ŸŒ
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 - Well, yes, you can iterate over all JSON properties and also get the values from the JSONObject itself. In this article, I'll show you how you can print all keys and value from JSON message using JSONOjbect and Iterator. Once you parse your JSON String using JSONParser, you get a JSONObject, but its of no use if you want a POJO i.e. a plain old Java object.
๐ŸŒ
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 - How to Iterate Through JSONObject in Java and Kotlin โ€“ Learn how to loop through a JSONObject and read key-value pairs in Java and Kotlin.
๐ŸŒ
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
๐ŸŒ
Codemia
codemia.io โ€บ knowledge-hub โ€บ path โ€บ how_to_iterate_over_a_jsonobject
How to iterate over a JSONObject?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Find elsewhere
๐ŸŒ
W3Docs
w3docs.com โ€บ java
How to iterate over a JSONObject?
You can also use the entrySet method to get a set of Map.Entry objects, which you can then iterate over using a for loop: import org.json.JSONObject; JSONObject obj = new JSONObject("{\"key1\": \"value1\", \"key2\": \"value2\"}"); for ...
๐ŸŒ
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 - ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonString); Iterator fieldNames = jsonNode.fieldNames(); While (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode value = jsonNode.get(fieldName); // Your logic here, for example: System.out.println(โ€œField: โ€œ + fieldName + โ€œ, Value: โ€œ + value); } } catch (Exception e) { e.printStackTrace(); } } }
๐ŸŒ
Example Code
example-code.com โ€บ java โ€บ json_array_iterate.asp
Java Iterate over JSON Array containing JSON Objects
Chilkat ย• HOME ย• Androidโ„ข ย• AutoIt ย• C ย• C# ย• C++ ย• Chilkat2-Python ย• CkPython ย• Classic ASP ย• DataFlex ย• Delphi DLL ย• Go ย• Java ย• JavaScript ย• Node.js ย• Objective-C ย• PHP Extension ย• Perl ย• PowerBuilder ย• PowerShell ย• PureBasic ย• Ruby ย• SQL Server ย• Swift ย• Tcl ย• Unicode C ย• Unicode C++ ย• VB.NET ย• VBScript ย• Visual Basic 6.0 ย• Visual FoxPro ย• Xojo Plugin
๐ŸŒ
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 - A quick guide to Iterate over a dynamic JSON string! This is the most common problem when we are working with the server-side development and we have to traverse JSON string dynamically as we often โ€ฆ
๐ŸŒ
Javatpoint
javatpoint.com โ€บ iterate-json-array-java
Iterate JSON Array Java - Javatpoint
Iterate JSON Array Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
๐ŸŒ
Tabnine
tabnine.com โ€บ home page โ€บ code โ€บ java โ€บ org.json.jsonarray
org.json.JSONArray.iterator java code examples | Tabnine
JSONParser parser = new JSONParser(); Object obj = parser.parse(new FileReader("d://sample.json")); JSONArray array = (JSONArray) obj; Iterator iter = array.iterator(); while (iter.hasNext()) { JSONObject json = (JSONObject) iter.next(); Iterator<String> keys = json.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); System.out.println("Key :" + key + " Value :" + json.get(key)); } }
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

Top answer
1 of 2
60

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

    Map<String,String> out = new HashMap<String, String>();

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
2 of 2
12

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

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.

}
๐ŸŒ
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.