用Java从谷歌地图api解析Json数组 [英] Parse Json array from google maps api in Java

查看:40
本文介绍了用Java从谷歌地图api解析Json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到这个 json 数组 https://maps.googleapis.com/maps/api/geocode/json?address=10115,germany 来自 Google Maps api.现在我想用 Java 解析它并从位置"部分获取lat"和lng",但我不知道如何获取它.

I get this json array https://maps.googleapis.com/maps/api/geocode/json?address=10115,germany from the Google Maps api. Now I want to parse it in Java and get from the part "location" the "lat" and "lng" but I don´t know how to get it.

推荐答案

这是代码 -

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonReader {



  public static void main(String[] args) throws ParseException  {


            InputStream inputStream = null;
            String json = "";

            try {           
                HttpClient client = new DefaultHttpClient();  
                HttpPost post = new HttpPost("https://maps.googleapis.com/maps/api/geocode/json?address=10115,germany");
                HttpResponse response = client.execute(post);
                HttpEntity entity = response.getEntity();
                inputStream = entity.getContent();
            } catch(Exception e) {
            }

            try {           
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"),8);
                StringBuilder sbuild = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sbuild.append(line);
                }
                inputStream.close();
                json = sbuild.toString();               
            } catch(Exception e) {
            }


            //now parse
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(json);
            JSONObject jb = (JSONObject) obj;

            //now read
            JSONArray jsonObject1 = (JSONArray) jb.get("results");
            JSONObject jsonObject2 = (JSONObject)jsonObject1.get(0);
            JSONObject jsonObject3 = (JSONObject)jsonObject2.get("geometry");
            JSONObject location = (JSONObject) jsonObject3.get("location");

            System.out.println( "Lat = "+location.get("lat"));
            System.out.println( "Lng = "+location.get("lng"));


        }
    }

输出-

Lat = 52.532614
Lng = 13.3777035

这篇关于用Java从谷歌地图api解析Json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆