简体   繁体   English

解析嵌套的JSON

[英]Parsing nested JSON

I have the following JSON: 我有以下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. 我尝试了与上面的代码相同的技巧来传递json.get(“location”),但这不起作用。 Please suggest how to make it work for location. 请建议如何使其适用于位置。

You need to detect when you are dealing with a (nested) Object using JsonNode#isObject : 您需要使用JsonNode#isObject检测何时处理(嵌套) Object

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. 因此,当您到达某个对象(例如location ,您printAll递归方式调用printAll以打印其所有内部值。

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

Since location is nested within registration , you need to use: 由于location嵌套在registration ,您需要使用:

registration_fields.get("location");

to get it. 为拿到它,为实现它。 But isn't it already processed by the while-loop, why do you need to get it separately? 但是它不是已经由while循环处理了,为什么你需要单独获取它?

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

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