简体   繁体   中英

How to parse JSONObjects in a JSONArray in Java?

I'm trying to read data from Floodlight's (an SDN controller) REST API and input that into other software's REST API. I have this which reads from Floodlight's REST API:

private JSONArray getFlData(String path) {
    try {
        logger.info("getData URL: " + path);
        URL url = new URL("http://localhost:8080" + path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        BufferedReader br = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));

        String inputline;
        StringBuffer response = new StringBuffer();
        while((inputline = br.readLine()) != null) {
             response.append(inputline);
        }
        JSONArray jsonr = new JSONArray(response.toString());
        br.close();
        conn.disconnect();
        return jsonr;
    }
    catch (MalformedURLException e) {
        logger.info("Bad URL (getData) " + path);
    }
    catch (IOException e) {
        logger.info("IOException (getData)" + path);
    }
    catch (JSONException e) {
        logger.info("Bad JSON (getData)" + path);
    }
    return null;
}

Then I'm parsing that information into lists:

    JSONArray flswitches = getFlData("/wm/core/controller/switches/json");
    List<String> switchDPIDlist = new ArrayList<String>();
    List<String> switchIPlist = new ArrayList<String>();
    for (int i = 0;i < flswitches.length();i++){
        try {
            switchDPIDlist.add(flswitches.getJSONObject(i).getString("switchDPID"));
            switchIPlist.add(flswitches.getJSONObject(i).getString("inetAddress"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Which works. However, when I try to do the same thing with the output regarding hosts in the network I'm running into problems. For reference, here's the CURL output for the simpler thing I can do it with:

curl http://127.0.0.1:8080/wm/core/controller/switches/json
[{"inetAddress":"/127.0.0.1:43663","connectedSince":1456305460978,"switchDPID":"00:00:00:00:00:00:00:01"},{"inetAddress":"/127.0.0.1:43664","connectedSince":1456305460981,"switchDPID":"00:00:00:00:00:00:00:03"},{"inetAddress":"/127.0.0.1:43665","connectedSince":1456305460984,"switchDPID":"00:00:00:00:00:00:00:02"}]

But when I try to use it with the more complex output like this, I run into problems:

curl http://127.0.0.1:8080/wm/device/
[{"entityClass":"DefaultEntityClass","mac":["86:2b:a2:f1:2b:9c"],"ipv4":["10.0.0.1"],"ipv6":[],"vlan":["0x0"],"attachmentPoint":[{"switchDPID":"00:00:00:00:00:00:00:02","port":1,"errorStatus":null}],"lastSeen":1456312407529},{"entityClass":"DefaultEntityClass","mac":["1e:94:63:67:1e:d1"],"ipv4":["10.0.0.3"],"ipv6":[],"vlan":["0x0"],"attachmentPoint":[{"switchDPID":"00:00:00:00:00:00:00:03","port":1,"errorStatus":null}],"lastSeen":1456312407625},{"entityClass":"DefaultEntityClass","mac":["06:d7:e0:c5:60:86"],"ipv4":["10.0.0.2"],"ipv6":[],"vlan":["0x0"],"attachmentPoint":[{"switchDPID":"00:00:00:00:00:00:00:02","port":2,"errorStatus":null}],"lastSeen":1456312407591},{"entityClass":"DefaultEntityClass","mac":["6e:c3:e4:5e:1f:65"],"ipv4":["10.0.0.4"],"ipv6":[],"vlan":["0x0"],"attachmentPoint":[{"switchDPID":"00:00:00:00:00:00:00:03","port":2,"errorStatus":null}],"lastSeen":1456312407626}]

For some reason just changing .getString("switchDPID") into .getString ("mac") flat out didn't work. Apparently the result from using "mac" is not a string, and I can't figure out what I should use. What am I doing wrong here and what should I change? Is it an issue with the mac-address format or is it something to do with the JSON format or something?

The value of mac is an array. So you'd have to use getJSONArray("mac") here. The exact syntax depends on the JSON library you are using.

You might want to have a look at Gson , which can convert JSON into regular Java objects and back again.

mac is a JSON array.

In this first example, the hierarchy is as follows

JSON Array -> JSON Object -> switchDPID

In the second one the hierarchy is

JSON Array -> JSON Object -> JSON Array ( mac ) -> data inside mac array.

If you see the JSON in tree structure, you can see the difference. I use http://www.jsoneditoronline.org/

You would have to fetch JSON Array ( mac ) first and then access it's first element for the data.

Here, mac is an array. Try to read it as an array and then get the first item in the array as string!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM