我有以下的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"
}
}
我使用下面的代碼來分析它:
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」),但這不起作用。請建議如何使它適用於位置。
你是什麼意思的「不起作用」,你會得到一個錯誤信息?如果是這樣,它說什麼? –
只是爲了清楚上面的代碼工作正常。但是當我嘗試應用位置字段相同的邏輯,然後行location_fields.getFieldNames()引發空指針異常。我相信我通過第一行 – Vik