Andreas Fritsch
Andreas Fritsch

Reputation: 242

get elements from json

I want to have a java list for all elements which are in the "in" or "out" element.

My json string:

{"in":[
       {"id":4,"ip":"192.168.0.20","pinSysNo":4,"pinSysName":"pg6","folderName":"gpio4_pg6","alias":"d","direction":"digital_in"},
       {"id":3,"ip":"192.168.0.20","pinSysNo":3,"pinSysName":"pb18","folderName":"gpio3_pb18","alias":"c","direction":"digital_out"}
      ],
 "out":[
       {"id":1,"ip":"192.168.0.20","pinSysNo":1,"pinSysName":"pg3","folderName":"gpio1_pg3","alias":"a","direction":"digital_in"},
       {"id":2,"ip":"192.168.0.20","pinSysNo":2,"pinSysName":"pb16","folderName":"gpio2_pb16","alias":"b","direction":"digital_in"}
            ]
}:""

Until now I did this way:

String message = json.findPath("in").textValue();

But this way can only access to the first hierarchy.

My json example show two elements in the "in" element. How I can get a list of these internal "in" elements?

Upvotes: 2

Views: 2132

Answers (2)

Andreas Fritsch
Andreas Fritsch

Reputation: 242

Thank you for your help. I found an other way to find all sub elements. Json example:

{"in":[
            {"id":4,"ip":"192.168.0.20","pinSysNo":4,"pinSysName":"pg6","folderName":"gpio4_pg6","alias":"d","direction":"digital_in"},
            {"id":3,"ip":"192.168.0.20","pinSysNo":3,"pinSysName":"pb18","folderName":"gpio3_pb18","alias":"c","direction":"digital_out"}
            ],
      "out":[
            {"id":1,"ip":"192.168.0.20","pinSysNo":1,"pinSysName":"pg3","folderName":"gpio1_pg3","alias":"a","direction":"digital_in"}
            ,{"id":2,"ip":"192.168.0.20","pinSysNo":2,"pinSysName":"pb16","folderName":"gpio2_pb16","alias":"b","direction":"digital_in"}
            ]
}

My solution:

JsonNode json = request().body().asJson();
Logger.info("JSON : " + json.findPath("in").findPath("id"));
Logger.info("JSON : " + json.findValues("in"));
List<JsonNode> ins = new org.json.simple.JSONArray();
ins = json.findValues("in");

for (final JsonNode objNode : ins) {

    for (final JsonNode element : objNode) {
        Logger.info(">>>>>" + element.findPath("id"));
        //create my object for database
    }
}

Now I can create my Object for the database. @eztam thank you

Upvotes: 0

eztam
eztam

Reputation: 3841

You could use the library JSONSimple in order to parse your JSON data by this code:

    JSONParser parser = new JSONParser();
    JSONObject o = (JSONObject) parser.parse(yourJsonAsString);
    JSONArray ins = (JSONArray) o.get("in");
    JSONArray outs = (JSONArray) o.get("out");

    String firstIpAddress = ((JSONObject) ins.get(0)).get("ip").toString();

Upvotes: 1

Related Questions