How to find node by name in Json Tree?

I am doing reverse geocoding using google geocoding API.

The results are returned in Json, which I process as follows -

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 the response contains Json returned from the server.

Is it possible to get a direct link to a node location without going through all this? For instance. there is something like -

new ObjectMapper().readValue(json).findNodeByName("lat").getFloatValue();

I read the documents in JsonNode and Tree in Jackson Api, but it seems that they are only useful if you want to cross the entire tree.

What would be the easiest way to get only a specific node?

+3
source share
2 answers

+1 to Michael Hickson for pointing out the geocoding library.

But after I looked through the docs, I finally found a solution -

ObjectMapper mapper = new ObjectMapper(); 

JsonNode rootNode = mapper.readTree(mapper.getJsonFactory()
                        .createJsonParser(response.getEntity(String.class)));

rootNode.findValue("lat").getDoubleValue();
+3
source

" node ", , , :

A: Java Google Geocoding API. HTTP- Java ( Apache HttpClient - ), JSON Jackson, -, , . : http://code.google.com/p/geocoder-java/. :

GeocodeResponse response = ... // Look at the example code on that site.
BigDecimal latitude = response.getResults().get(0).getGeometry().getLocation().getLat()

B: , JSON "". , JSON. - :

public class ResultSet {
  public List<Result> results;
}

public class Result {
  public Geometry geometry;
}

public class Geometry {
  public Location location;
}

public class Location {
  public double latitude;
  public double longitude;
}

String json = ... // The raw JSON you currently have.
Response response = new ObjectMapper().readValue(json, Response.class);
double latitude = response.results.get(0).geometry.location.latitude;
+1

All Articles