How to find a node by name in a Json Tree?
jackson, java, json
Solution
+1 to Michael Hixson for pointing out the geocoding library.
But, after digging through the docs I've finally found the solution -
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(mapper.getJsonFactory()
.createJsonParser(response.getEntity(String.class)));
rootNode.findValue("lat").getDoubleValue();
Problem
I am doing inverse geocoding using google geocoding APIs. The results are returned in Json which I'm parsing in following manner - ``` Map<String, Object> parsedJson = new ObjectMapper().readValue( response.getEntity(String.class), new TypeReference<Map<String, Object>>() { }); List<Object> results = (List<Object>) parsedJson.get("results"); // From first result get geometry details Map<String, Object> geometry = (Map<String, Object>) ((Map<String, Object>) results .get(0)).get("geometry"); Map<String, Object> location = (Map<String, Object>) geometry .get("location"); Map<String, Double> coordinates = new HashMap<String, Double>(); coordinates.put("latitude", (Double) location.get("lat")); coordinates.put("longitude", (Double) location.get("lng")); ``` Where response contains the Json returned from server. Is it possible to get a direct reference to the location node without going through all this? E.g. is there something like - ``` new ObjectMapper().readValue(json).findNodeByName("lat").getFloatValue(); ``` I have read the docs on JsonNode and Tree in Jackson Api but it seems they are useful only if you want to traverse the entire tree. What would be the easiest way to fetch only a particular node?