1

I am using Jackson to parse some json. An snippet from this json is as follows:

},
"1/1/0": {
  "event": "status",
  "name": "Alarm Status",
  "type": "Alarm",
  "location": "Hall"
},
"1/1/1": {
  "event": "status",
  "name": "Smoke Alarm Status",
  "type": "Alarm",
  "location": "Hall"
},

I've happily managed to extract the data for each 'object', but I am struggling to obtain the 'name' for each object. In the example above, this would be '1/1/0' and '1/1/1'. I do so in the following way:

final JsonNode node = parser.parseToNode(configJson);
final JsonNode sensorsChild = node.get("sensors");

    for (JsonNode root : sensorsChild) {
                    final String event = root.get("event").asText();
                    final String name = root.get("name").asText();
                    final String type = root.get("type").asText();
                    final String location = root.get("location").asText();
    }

I want another line in the the for loop which is something like:

final String id = root.getNodeFieldName();

which would yield '1/1/0' and '1/1/1' respectively. Thanks

Joe
  • 123
  • 2
  • 3
  • 10
  • can you post your complete json ? – Derrick Nov 02 '16 at 04:28
  • @DerickDaniel I can't unfortunately, as it's 1000s of lines long, but the snippet should give a good indication of what I'm up against. – Joe Nov 02 '16 at 08:52
  • Does that help? http://stackoverflow.com/questions/7653813/jackson-json-get-node-name-from-json-tree – Tomalak Nov 02 '16 at 09:37
  • @Tomalek I'm not sure it does. I've had a look at that before and couldn't get the 'for' loop to work with the error 'for-loop not applicable to the expression type' – Joe Nov 02 '16 at 10:52

1 Answers1

3

You can do something like this, iterate over the root node to get the required key fields ('1/1/0' and '1/1/1') and data for each object through the nested while loop and for-loop respectively.

final JsonNode node = parser.parseToNode(configJson); 

for (JsonNode root : node) {

            Iterator<String> itr = root.getFieldNames();
                while (itr.hasNext()) {  //to get the key fields
                String key_field = itr.next();
                }

            for (JsonNode n : node.get("sensors")) {  //to get each object
                final String event = root.get("event").asText();
                final String name = root.get("name").asText();
                final String type = root.get("type").asText();
                final String location = root.get("location").asText();
                }
   }

It would be easier if you have a pojo class mapped with your json to perform these operations when you are using jackson library.

Derrick
  • 3,669
  • 5
  • 35
  • 50