32

I am trying to iterate over a json object using json simple. I have seen answers where you can do a getJSONObject("child") from

{ "child": { "something": "value", "something2": "value" } }

But what if I just have something

{
"k1":"v1",
"k2":"v2",
"k3":"v3"
} 

And want to iterate over that json object. This:

Iterator iter = jObj.keys();

Throws:

cannot find symbol
symbol  : method keys()
location: class org.json.simple.JSONObject
mehdi
  • 340
  • 4
  • 17
Z2VvZ3Vp
  • 7,033
  • 6
  • 21
  • 35

4 Answers4

66

Assuming your JSON object is saved in a file "simple.json", you can iterate over the attribute-value pairs as follows:

JSONParser parser = new JSONParser();

Object obj = parser.parse(new FileReader("simple.json"));

JSONObject jsonObject = (JSONObject) obj;

for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(jsonObject.get(key));
}
M A
  • 71,713
  • 13
  • 134
  • 174
  • Thanks solved the problem! Not sure why I got downvoted for the question. – Z2VvZ3Vp Jun 23 '14 at 20:19
  • Spent most of my morning trying to find a solution to access json objects dynamically. Thank you for positing this! – canadiancreed Jul 29 '15 at 16:57
  • @hadi: Your version of [JSON-java](https://github.com/stleary/JSON-java) is probably too old. keySet is available in any version after 27 Oct 2012. – JonnyJD Apr 01 '16 at 12:18
  • Its important to note this is the most current answer. A lot of other answers involved just `jsonObject.keys()` which is in fact not current. You must now use `jsonObject.keySet().iterator()` – mewc Mar 08 '18 at 00:58
  • 1
    i did the same block of code but receiving this error: Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject – Haim Sabag Jun 08 '20 at 14:41
  • due to the keySet I get it in the wrong order, are there any options to get the keys as they are? – neobatman Jun 17 '20 at 12:17
6

You can do like this

String jsonstring = "{ \"child\": { \"something\": \"value\", \"something2\": \"value\" } }";
JSONObject resobj = new JSONObject(jsonstring);
Iterator<?> keys = resobj.keys().iterator();
while(keys.hasNext() ) {
    String key = (String)keys.next();
    if ( resobj.get(key) instanceof JSONObject ) {
        JSONObject xx = new JSONObject(resobj.get(key).toString());
        Log.d("res1",xx.getString("something"));
        Log.d("res2",xx.getString("something2"));
    }
}
MUmla
  • 445
  • 1
  • 8
  • 26
Mojo Jojo
  • 188
  • 4
  • 16
0

In Java 8 we can use lambdas

void handleJSONObject(JSONObject jsonObject) {
jsonObject.keys().forEachRemaining(key -> {
    Object value = jsonObject.get(key);
    logger.info("Key: {0}\tValue: {1}", key, value);
  }
}
Saurabh Verma
  • 627
  • 1
  • 14
  • 27
0

Below is the code to iterate through org.google.jso.JsonElemet set and filter out the specific JsonElement by key:

Predicate<Map.Entry<String, JsonElement>> keyPredicate = a -> a.getKey().equalsIgnoreCase(jsonAttributeKey);
        Predicate<Map.Entry<String, JsonElement>> valuePredicate = a -> a.getValue()!= null && !a.getValue().isJsonNull();
        return responseJson.getAsJsonObject().entrySet().stream()
                .filter(keyPredicate.and((valuePredicate)))
                .findAny()
                .orElseThrow(() -> {
                    System.out.println(jsonAttributeKey +" tag not exist in the json");
                    return NGPExceptionFactory.getNGPException(errorCode);
                })
                .getValue();
Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69