Iterate Over Keys of JSONObject – Java

JSON’s are commonly used in many Java programs, with most common libraries being org.json and com.google.gson. The examples below show how to iterate over keys of both json objects in Java 8.

With com.json.JSONObject

jsonObject.keys().forEachRemaining(key -> System.out.println(key));
jsonObject.keySet().forEach(key -> System.out.println(key));
jsonObject.keySet().parallelStream().forEach(key -> System.out.println(key));

The above methods simply iterate through all the first level keys within a JSONObject and print them to the console. The .keys() function returns an Iterator and does not support parallel execution. The .keySet() function returns a Set of the keys and maybe integrated in a single thread or in parallel.

If printing to console was the only objective, the lambda expression can be better used as


With com.google.gson.JsonObject

jsonObject.entrySet().forEach(entry -> System.out.println(entry.getKey()));
jsonObject.entrySet().parallelStream().forEach(entry -> System.out.println(entry.getKey()));

The Google’s JsonObject implementation provides for iteration over the key-value pairs inside the JsonObject. So it is not just the key, but the value also can be obtained using a single iteration.

jsonObject.entrySet().parallelStream().forEach(entry -> {
%d bloggers like this: