【问题标题】:JSON parsing of Google Maps API in Android AppAndroid App中Google Maps API的JSON解析
【发布时间】:2011-11-06 10:16:27
【问题描述】:

我正在尝试使用谷歌地图 API 来获取方向时间。我希望创建一个 url,获取 JSON 响应,然后检查该响应的旅行持续时间。创建 JSON 对象后,我无法导航它。对我来说,这表明我要么搞砸了获取响应或导航 JSON 对象。如果您能查看我从网络上的教程中拼凑的代码片段,我将不胜感激。

此代码旨在获取响应。它被 try/catch 包围,并且没有触发任何错误。

      String stringUrl = <URL GOES HERE>;

      URL url = new URL(stringUrl);
      HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
      if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
      {
          BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
          String strLine = null;
          while ((strLine = input.readLine()) != null)
          {
              response.append(strLine);
          }
          input.close();
      }
      String jsonOutput = response.toString();

此代码旨在获取该输出并将其解析为最终字符串,持续时间,受this stackoverflow answer 的启发,用于类似问题。

        JSONObject jsonObject = new JSONObject(jsonOutput);
        JSONObject routeObject = jsonObject.getJSONObject("routes");
        JSONObject legsObject = routeObject.getJSONObject("legs");
        JSONObject durationObject = legsObject.getJSONObject("duration"); 
        String duration = durationObject.getString("text");

我在第二个块的第二行捕获了一个 JSON 异常。任何人都可以帮助解决这个问题吗?或者也许建议一种更简单的方法来获取相同的数据?

编辑:感谢这里的第一个有用的答案(来自 aromero),后半部分现在看起来像:

    JSONObject jsonObject = new JSONObject(responseText);
    JSONArray routeObject = jsonObject.getJSONArray("routes");
    JSONArray legsObject = routeObject.getJSONArray(2); ***error***
    JSONObject durationObject = legsObject.getJSONObject(1);
        String duration = durationObject.getString("text");

但它仍然抛出一个 JSON 异常,只是现在它在第三行之后。我确信这很容易解决,但我非常感谢您的帮助。

示例 JSON 文件的相关部分如下所示:

{
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 34.092810,
               "lng" : -118.328860
            },
            "southwest" : {
               "lat" : 33.995590,
               "lng" : -118.446040
            }
         },
         "copyrights" : "Map data ©2011 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "12.9 mi",
                  "value" : 20807
               },
               "duration" : {
                  "text" : "27 mins",
                  "value" : 1619
               },

【问题讨论】:

    标签: android json google-maps-api-3


    【解决方案1】:

    “routes”是一个数组,不用getJSONObject,用getJSONArray

    “legs”也是一个数组。

    JSONObject jsonObject = new JSONObject(responseText);
    
    // routesArray contains ALL routes
    JSONArray routesArray = jsonObject.getJSONArray("routes");
    // Grab the first route
    JSONObject route = routesArray.getJSONObject(0);
    // Take all legs from the route
    JSONArray legs = route.getJSONArray("legs");
    // Grab first leg
    JSONObject leg = legs.getJSONObject(0);
    
    JSONObject durationObject = leg.getJSONObject("duration");
    String duration = durationObject.getString("text");
    

    【讨论】:

    • 我想你已经确定我做错了什么。仍在讨论细节。当我修复它时,我会回复它,除非有人打败我。
    • Routes 是一个数组,我假设谷歌正在返回一个可能的路线列表。所以你需要抓住其中一个,或者对所有这些都做些什么。你想做什么?
    • 太棒了!感谢您对原始答案的编辑,我非常感谢您的牵手。我真的不明白 JSON 的语法/间距,你说得非常清楚。非常感谢!
    【解决方案2】:

    我还尝试在 Android 中使用 Google 的 Direction Api。 所以我做了一个开源项目来帮助做到这一点。 你可以在这里找到它:https://github.com/MathiasSeguy-Android2EE/GDirectionsApiUtils

    它是如何工作的,绝对简单:

    public class MainActivity extends ActionBarActivity implements DCACallBack{
    /**
     * Get the Google Direction between mDevice location and the touched location using the     Walk
     * @param point
     */
    private void getDirections(LatLng point) {
         GDirectionsApiUtils.getDirection(this, startPoint, endPoint, GDirectionsApiUtils.MODE_WALKING);
    }
    
    /*
     * The callback
     * When the directions is built from the google server and parsed, this method is called and give you the expected direction
     */
    @Override
    public void onDirectionLoaded(List<GDirection> directions) {        
        // Display the direction or use the DirectionsApiUtils
        for(GDirection direction:directions) {
            Log.e("MainActivity", "onDirectionLoaded : Draw GDirections Called with path " + directions);
            GDirectionsApiUtils.drawGDirection(direction, mMap);
        }
    }
    

    【讨论】:

    • 我可以将你的整个代码从 Github 实现到我的商业应用程序吗?
    猜你喜欢
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2020-10-07
    相关资源
    最近更新 更多