javajsonjson-simple

Iterate through JSONObject from root in json simple


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

Solution

  • 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));
    }