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.

}
🌐
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('