简体   繁体   English

如何使用Jackson解析嵌套的JSON(无论是递归还是迭代)?

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

I have a sample JSON payload that looks like this: 我有一个示例JSON有效负载,如下所示:

 {"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... 而且,可能有JSON在其中包含更多嵌套的JSON ...意味着某些JSON可能没有嵌套的JSON,而有些可能有多个...

Is there a way to recursively parse all the key / value pairs from a JSON payload using Jackson? 有没有办法使用Jackson以递归方式解析JSON有效负载中的所有键/值对?

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. 下面的代码将帮助您使用Jackson库解析和获取所需的值。

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. 如果我是这段代码的开发者,我宁愿用一个现有的JSON库(比如Jackson或GSON)来完成这个。

Below is one of the examples, to parse the JSON representation of list of objects. 下面是一个示例,用于解析对象列表的JSON表示。 URL: http://www.studytrails.com/java/json/java-jackson-Serialization-list.jsp 网址: http//www.studytrails.com/java/json/java-jackson-Serialization-list.jsp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM