Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing nested JSON

Tags:

java

json

jackson

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 am using the following code to parse 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 fine and it print all the values except for location which is kind of another level of nesting. I tried the same trick as above code to pass json.get("location") but that does not work. Please suggest how to make it work for location.

like image 425
Vik Avatar asked Sep 15 '12 00:09

Vik


1 Answers

You need to detect 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'll call the printAll recursively to print all its inner values.

org.codehaus.jackson.JsonNode json = new ObjectMapper().readTree(jsonString);
org.codehaus.jackson.JsonNode registration_fields = json.get("registration");
printAll(registration_fields);
like image 164
João Silva Avatar answered Sep 23 '22 05:09

João Silva