SeanM SeanM - 1 year ago 70
JSON Question

Iterate JSON and get fields from JSON

I've tried different solutions but I'm not able to iterate through this JSON and/or get direct specific values.

Could any one help on:

  • Iterating through all the fields sequentially.

  • Getting direct access to some fields (eg. when getting this response, access directly to
    where its value equals


I tried to use
but any other library would be ok.


Answer Source

You will have to check the structure of your JSON Object and create a structure for the entities you encounter accordingly. For instance, the first thing in your JSON object is an array, so this is the first thing you should care about. Imagine it as a continuous encapsulation. Check the code below for more information.

JSONObject jobj = new JSONObject(stringJson);
JSONArray flowNodeInv = jobj.getJSONArray("flow-node-inventory:flow");
    for (int i = 0; i < flowNodeInv.length(); i++){
          JSONObject segment = (JSONObject) flowNodeInv.get(i);
          JSONObject stats = segment.getJSONObject("opendaylight-flow-statistics:flow-statistics");

        int number = stats.getInt("packet-count");

       System.out.println("packet-count: "+ number);}