gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:11:27 27 4
gpt4 key购买 nike

我编写了一些代码来解析我的 Android 程序收到的 Google 距离矩阵 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"
}

这是我用来提取距离值的代码:

    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;
}

谢谢!

最佳答案

我向你推荐 GSON (http://code.google.com/p/google-gson/),它将 JSON 文本解析为 java 类实例,并且可以将类实例转换为 JSON 文本

关于android - 使用 Android 解析 JSON 的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9669974/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com