7

我有以下 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"
  }
}

我正在使用以下代码来解析它:

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);
}

这工作正常,它打印除了位置之外的所有值,这是另一种嵌套级别。我尝试了与上面代码相​​同的技巧来传递 json.get("location") 但这不起作用。请建议如何使其适用于位置。

4

2 回答 2

15

您需要检测何时使用(嵌套)Object处理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);
         }
     }
}

因此,当您到达一个对象时,例如location,您将printAll递归调用以打印其所有内部值。

org.codehaus.jackson.JsonNode json = new ObjectMapper().readTree(jsonString);
org.codehaus.jackson.JsonNode registration_fields = json.get("registration");
printAll(registration_fields);
于 2012-09-15T01:05:48.157 回答
1

由于location嵌套在 内registration,您需要使用:

registration_fields.get("location");

为拿到它,为实现它。但是不是已经被while循环处理过了,为什么还要单独获取呢?

于 2012-09-15T01:05:50.933 回答