使用Android解析JSON的最有效方法

pjd*_*pjd 7 android json

我编写了一些代码来解析我的Android程序收到的Google Distance Matrix JSON响应.我唯一感兴趣的数据是"距离""值"节点.

我的代码有效,但似乎必须有一个更简单的方法来做到这一点.距离值节点嵌套在JSON内部,但是真的有必要遍历JSON的每一层才能到达你想要的字段吗?

这是我的JSON响应:

{
"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"
}
Run Code Online (Sandbox Code Playgroud)

这是我用来拉出距离值的代码:

    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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

vip*_*zer 6

我建议您使用GSON(http://code.google.com/p/google-gson/)将JSON文本解析为java类实例,并将类实例转换为JSON文本


mma*_*len 6

杰克逊是另一个很好的第三方解析器http://jackson.codehaus.org/.看起来这里有一个比较,http://www.cowtowncoder.com/blog/archives/2009/09/entry_326.html.

这是一个使用树遍历的示例,不确定它是否比您正在做的更容易,http://wiki.fasterxml.com/JacksonTreeModel


cDe*_*r32 3

除非您想编写自定义正则表达式来搜索 json 字符串,否则这将是访问它的最佳方式(也是最简单的方式)。您是否有理由认为需要“更有效”地访问它?