You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Volley访问JSON数据?及提取指定JSON中features内center的经纬度

没问题,这两个问题我来一步步帮你解决:

一、如何使用Volley访问JSON数据?

使用Volley访问JSON数据其实很直观,分为这几个关键步骤:

  • 1. 添加Volley依赖
    首先确保你的Android项目引入了Volley库,在模块级别的build.gradle(通常是app/build.gradle)的dependencies块中添加:

    implementation 'com.android.volley:volley:1.2.1'
    

    同步项目后,Volley就可以正常使用了。

  • 2. 创建RequestQueue
    RequestQueue是Volley管理网络请求的核心类,你可以在Activity或Application中初始化它。这里举个Activity内的示例:

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    
  • 3. 创建JSON请求并处理响应
    根据返回的JSON类型(对象或数组),选择JsonObjectRequest或JsonArrayRequest。针对你提供的Mapbox接口,返回的是JSON对象,所以用JsonObjectRequest:

    String url = "https://api.mapbox.com/geocoding/v5/mapbox.places/Los%20Angeles.json?access_token=REDACTED&limit=1";
    
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
            Request.Method.GET,
            url,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    // 成功获取JSON后的处理逻辑,后面会讲如何提取经纬度
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // 请求出错时的处理,比如打印错误信息或提示用户
                    error.printStackTrace();
                }
            }
    );
    
    // 将请求加入队列执行
    requestQueue.add(jsonObjectRequest);
    
二、从指定JSON数据中提取经纬度值

你提到的JSON结构里,经纬度存放在features数组下的center数组内,注意Mapbox返回的center格式是[经度(longitude), 纬度(latitude)],别搞反顺序哦。我们可以在上面的onResponse方法中添加提取逻辑:

@Override
public void onResponse(JSONObject response) {
    try {
        // 获取features数组
        JSONArray featuresArray = response.getJSONArray("features");
        if (featuresArray.length() > 0) {
            // 取第一个元素(因为limit=1,结果只有一个)
            JSONObject firstFeature = featuresArray.getJSONObject(0);
            // 获取center数组
            JSONArray centerArray = firstFeature.getJSONArray("center");
            
            // 提取经纬度
            double longitude = centerArray.getDouble(0);
            double latitude = centerArray.getDouble(1);
            
            // 这里就可以使用经纬度了,比如打印或者展示到UI上
            Log.d("Location", "经度:" + longitude + ",纬度:" + latitude);
        }
    } catch (JSONException e) {
        // 处理JSON解析异常,避免结构不符导致崩溃
        e.printStackTrace();
    }
}

记得把URL里的REDACTED替换成你自己的Mapbox access token,另外一定要加异常捕获,防止因JSON结构变化或缺失导致崩溃。

内容的提问来源于stack exchange,提问作者user10971736

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:18:11