简体   繁体   中英

How to parse nested JSON using Jackson (whether recursively or iteratively)?

I have a sample JSON payload that looks like this:

 {"timestamp": 1427394360, "device": {"user-agent": "Mac OS 10.10.2 2.6 GHz Intel Core i7"}}

I parse it and get the key / value pairs using this:

 Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();

 while (fieldsIterator.hasNext()) {
    Map.Entry<String,JsonNode> field = fieldsIterator.next();
    key = field.getKey();
    value = field.getValue();
    System.out.println("Key: " + key);
    System.out.println("Value: " + value);
 }

This outputs:

Key: timestamp
Value: 1427394360

Key: device
Value: {"user-agent": "Mac OS 10.10.2 2.6 GHz Intel Core i7"}

How can I set it up so I can parse out the key / value pair inside the device key to become:

Key: "user-agent"
Value: "Mac OS 10.10.2 2.6 GHz Intel Core i7"

And also, there might be JSON that has even more nested JSON inside it... Meaning that some JSON might have no nested JSON and some might have multiple...

Is there a way to recursively parse all the key / value pairs from a JSON payload using Jackson?

Thank you for taking the time to read this...

You can place your code in a method and make a recursive call if the value is container (Ex: array or object).

For example:

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    final JsonNode rootNode = mapper.readTree(" {\"timestamp\": 1427394360, \"device\": {\"user-agent\": \"Mac OS 10.10.2 2.6 GHz Intel Core i7\"}}");
    print(rootNode);
}

private static void print(final JsonNode node) throws IOException {
    Iterator<Map.Entry<String, JsonNode>> fieldsIterator = node.getFields();

    while (fieldsIterator.hasNext()) {
        Map.Entry<String, JsonNode> field = fieldsIterator.next();
        final String key = field.getKey();
        System.out.println("Key: " + key);
        final JsonNode value = field.getValue();
        if (value.isContainerNode()) {
            print(value); // RECURSIVE CALL
        } else {
            System.out.println("Value: " + value);
        }
    }
}

Below code will help you to parse and fetch required value using Jackson library.

public class GetJsonKeyValueUsingRecursion {

 static String value;

 public static void main(String[] args) throws JsonProcessingException, IOException {

  JsonNode rootPage = new ObjectMapper()
   .readTree(new File("C:/employee.json"));
  // System.out.println(rootPage);


  JsonNode std = rootPage.path("Student");
  System.out.println(std);
  //Call recursive json parser with node name and key name whose values is required
  String value = parseJsonRecursively(std, "SSC");

  System.out.println("Searched value: " + value);
 }
 static boolean flag = false;
 private static String parseJsonRecursively(JsonNode rootNode, String expectedKey) {

  value = null;
  try {

   if (rootNode.isArray() && rootNode.isContainerNode()) {
    System.out.println("In array Root node is: " + rootNode);

    for (JsonNode objNode: rootNode) {

     if (flag) {
      break;
     } else if (objNode.isValueNode()) {

     } else {

      parseJsonRecursively(objNode, expectedKey);
     }
    }

   } else if (rootNode.isValueNode()) {
    value = rootNode.asText();
    return value;
   } else if (rootNode.isContainerNode()) {

    Iterator < String > subItemItrator = rootNode.fieldNames();

    while (subItemItrator.hasNext() && !flag) {

     String targetKey = subItemItrator.next();

     System.out.println("Target Key: " + targetKey);

     if (targetKey.equals(expectedKey)) {
      value = rootNode.path(targetKey).asText();

      System.out.println("Matched :-----> " + targetKey + " = " + expectedKey + " Value: " + value);
      flag = true;
      return value;


     } else if (!rootNode.path(targetKey).isValueNode() && flag == false) {
      parseJsonRecursively(rootNode.path(targetKey), expectedKey);

     }

    }

   }

  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return value;
 }
}

If I was the developer of this code, I would rather user an existing JSON library (such as Jackson or GSON) to accomplish this.

Below is one of the examples, to parse the JSON representation of list of objects. URL: http://www.studytrails.com/java/json/java-jackson-Serialization-list.jsp

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