Parsing Nested JSON

I have the following JSON:

{ "registration": { "name": "Vik Kumar", "first_name": "Vik", "last_name": "Kumar", "bloodGroup": "B-", "gender": "male", "birthday": "10\/31\/1983", "email": "vik.ceo\u0040gmail.com", "cellPhone": "1234123456", "homePhone": "1234123457", "officePhone": "1234123458", "primaryAddress": "jdfjfgj", "area": "jfdjdfj", "location": { "name": "Redwood Shores, California", "id": 103107903062719 }, "subscribe": true, "eyePledge": false, "reference": "fgfgfgfg" } } 

I use the following code to analyze it:

 JsonNode json = new ObjectMapper().readTree(jsonString); JsonNode registration_fields = json.get("registration"); Iterator<String> fieldNames = registration_fields.getFieldNames(); while(fieldNames.hasNext()){ String fieldName = fieldNames.next(); String fieldValue = registration_fields.get(fieldName).asText(); System.out.println(fieldName+" : "+fieldValue); } 

This works great and prints all values ​​except the location, which is another level of nesting. I tried the same trick as above to pass json.get ("location"), but that doesn't work. Please suggest how to do this for the location.

+7
source share
2 answers

You need to determine when you are dealing with a (nested) Object using JsonNode#isObject :

 public static void printAll(JsonNode node) { Iterator<String> fieldNames = node.getFieldNames(); while(fieldNames.hasNext()){ String fieldName = fieldNames.next(); JsonNode fieldValue = node.get(fieldName); if (fieldValue.isObject()) { System.out.println(fieldName + " :"); printAll(fieldValue); } else { String value = fieldValue.asText(); System.out.println(fieldName + " : " + value); } } } 

Thus, when you reach an object, such as location , you will recursively call printAll to print all of its internal values.

 org.codehaus.jackson.JsonNode json = new ObjectMapper().readTree(jsonString); org.codehaus.jackson.JsonNode registration_fields = json.get("registration"); printAll(registration_fields); 
+15
source

Since location nested in registration , you need to use:

 registration_fields.get("location"); 

to get it. But isn't it being processed by the while-loop, why do you need to get it separately?

+1
source

All Articles