获得"几何"来自谷歌API结果

时间:2017-03-10 09:35:03

标签: java json servlets gson

到目前为止,使用我的代码,我可以将结果作为JsonObject获取。但是,我试图根据我输入的邮政编码获取位置的坐标。如何检索" lat"和" lng"作为Strings / JsonElements?如果你能给我一些见解,真的很感激。谢谢!

   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");

    //the JSON builder
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String restaurant = request.getParameter("r");
        String customer = request.getParameter("c");

        //Get coordinates of the restaurant 
        String longLatApi = "https://maps.googleapis.com/maps/api/geocode/json?address=" + restaurant;
        URL url = new URL(longLatApi);
        URLConnection connection = url.openConnection();
        connection.addRequestProperty("Referer", longLatApi);

        String line;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        String jsonString = builder.toString();
        JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();

        out.println(gson.toJson(obj));

1 个答案:

答案 0 :(得分:0)

JsonElement及其子类具有很好的方法来迭代不同种类的JSON元素:null,一个原语(数字,字符串文字和布尔值),一个JSON对象或一个JSON数组。知道响应JSON文档的确切结构,您可以非常直接地提取子元素:

final URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=Greenwich");
// Let Gson parse the JSON input stream without expensive intermediate strings
try ( final Reader reader = new BufferedReader(new InputStreamReader(url.openStream())) ) {
    final JsonParser jsonParser = new JsonParser();
    // Extract the `results` array
    final JsonArray resultsJsonArray = jsonParser.parse(reader)
            .getAsJsonObject()
            .get("results")
            .getAsJsonArray();
    // Iterate over each result array element
    for ( int i = 0; i < resultsJsonArray.size(); i++ ) {
        final JsonObject resultJsonObject = resultsJsonArray.get(i).getAsJsonObject();
        System.out.println(resultJsonObject.getAsJsonPrimitive("formatted_address").getAsString());
        // Picking up the `geometry` property as a JSON object
        final JsonObject geometryJsonObject = resultJsonObject.get("geometry").getAsJsonObject();
        // And dumping the location
        final JsonObject locationJsonObject = geometryJsonObject.get("location").getAsJsonObject();
        dumpLocationJsonObject("Location", locationJsonObject);
        final JsonElement boundsJsonElement = geometryJsonObject.get("bounds");
        // There can be a `bounds` object with two additional properties
        if ( boundsJsonElement != null && !boundsJsonElement.isJsonNull() ) {
            final JsonObject boundsJsonObject = boundsJsonElement.getAsJsonObject();
            dumpLocationJsonObject("North/East", boundsJsonObject.get("northeast").getAsJsonObject());
            dumpLocationJsonObject("South/West", boundsJsonObject.get("southwest").getAsJsonObject());
        }
    }
}
private static void dumpLocationJsonObject(final String name, final JsonObject location) {
    final double latitude = location.getAsJsonPrimitive("lat").getAsDouble();
    final double longitude = location.getAsJsonPrimitive("lng").getAsDouble();
    System.out.println("\t" + name + ": (" + latitude + "; " + longitude + ")");
}

输出:

Greenwich, London SE10, UK  
    Location: (51.48257659999999; -0.0076589)  

作为替代方法,您可以将自定义JSON定义为Java类映射,以便将JSON文档反序列化为自定义类实例,而不仅仅是JsonElement(类似gson.fromJson(reader, customType))。这两种方法都有利有弊。