最有效的方法来解析JSON采用Android [英] Most Efficient Way to Parse JSON Using Android

查看:138
本文介绍了最有效的方法来解析JSON采用Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一些code解析我的Andr​​oid程序收到谷歌距离矩阵JSON响应。唯一的数据块,我感兴趣的是,在距离,价值的节点。

I've written some code to parse the Google Distance Matrix JSON response received by my Android program. The only piece of data I'm interested in is in the "distance" "value" node.

我的code的作品,但好像必须有一个更简单的方法来做到这一点。距离值节点是嵌套pretty的JSON的内心深处,却是真的有必要去通过JSON的每一层得到你想要的领域?

My code works, but it seems like there must be an easier way to do this. The distance value node is nested pretty deep inside the JSON, but is it really necessary to go through every layer of the JSON to get to the field you want?

下面是我的JSON响应:

Here's my JSON response:

{
"destination_addresses" : [
  "5660 Baltimore National Pike, Ingleside Shopping Center, Catonsville, MD 21228, USA"
],
"origin_addresses" : [ "Hilltop Cir, Baltimore, MD 21250, USA" ],
"rows" : [
  {
     "elements" : [
        {
           "distance" : {
              "text" : "3.1 mi",
              "value" : 4922 <--THE FIELD I WANT TO EXTRACT
           },
           "duration" : {
              "text" : "11 mins",
              "value" : 666
           },
           "status" : "OK"
        }
     ]
  }
],
"status" : "OK"
}

这里是code我用来拉出来的距离值:

And here is the code I used to pull out the distance value:

    private double extractDistance(JSONObject json) {
    JSONArray rowsArray = null;
    double distanceInMiles = -1;
    try {
        // Getting Array of Distance Matrix Results
        rowsArray = json.getJSONArray("rows");
        JSONObject rowsObject = rowsArray.getJSONObject(0);//only one element in this array
        JSONArray elementsArray = rowsObject.getJSONArray("elements");
        JSONObject elementsObject = elementsArray.getJSONObject(0);//only one element in this array
        JSONObject distanceObject = elementsObject.getJSONObject("distance");
        distanceInMiles = (distanceObject.getDouble("value"))/1609.344; //distance in meters converted to miles
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    return distanceInMiles;
}

谢谢!

推荐答案

除非你想进入编写自定义的正前pression搜索的JSON字符串,是这将是访问它的最好办法(和最容易的)。有没有你觉得你需要更有效地访问它?

Unless you want to go into writing a custom regular expression to search the json string, yes that's going to be the best way of accessing it (and the easiest). Is there a reason you feel you need to access it 'more efficiently'?

这篇关于最有效的方法来解析JSON采用Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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