[java] JSON - Iterate through JSONArray

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": {
    "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"
        }

    ]
}

}       

This is how far I have come:

JSONObject object = new JSONObject("json-file.json");
JSONObject getObject = object.getJSONObject("JObjects");
JSONArray getArray = getObject.getJSONArray("JArray1");

for(int i = 0; i < getArray.size(); i++)
{
      JSONObject objects = getArray.getJSONArray(i);
      //Iterate through the elements of the array i.
      //Get thier value.
      //Get the value for the first element and the value for the last element.
}

Is it possible to do something like this?

The reason I want to do it like this is because the arrays in the file have a different number of elements.

This question is related to java json

The answer is


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


You could try my (*heavily borrowed from various sites) recursive method to go through all JSON objects and JSON arrays until you find JSON elements. This example actually searches for a particular key and returns all values for all instances of that key. 'searchKey' is the key you are looking for.

ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values

    private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {

    //OBJECT
    if(element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();

        //loop through all elements in object

        for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
            JsonElement array = entry.getValue();
            findMyKeyValue(array, entry.getKey(), searchKey);

        }

    //ARRAY
    } else if(element.isJsonArray()) {
        //when an array is found keep 'key' as that is the array's name i.e. pass it down

        JsonArray jsonArray = element.getAsJsonArray();

        //loop through all elements in array
        for (JsonElement childElement : jsonArray) {
            findMyKeyValue(childElement, key, searchKey);
        }

    //NEITHER
    } else {

        //System.out.println("SKey: " + searchKey + " Key: " + key );

            if (key.equals(searchKey)){
                listOfValues.add(element.getAsString());
            }
    }
    return listOfValues;
}

for(int i = 0; i < getArray.size(); i++){
      Object object = getArray.get(i);
      // now do something with the Object
}

You need to check for the type:

The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. [Source]

In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names() to retrieve the individual keys.


JsonArray jsonArray;
Iterator<JsonElement> it = jsonArray.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}