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

如何访问OpenWeatherMap API预报数据?代码示例求助

解决OpenWeatherMap Forecast API的数据访问问题

我来帮你搞定Forecast API的数据解析问题!首先得先搞懂OpenWeatherMap的Forecast API返回的JSON结构,然后结合你的Android代码一步步提取需要的数据。

先明确API返回的核心结构

OpenWeatherMap的5天预报API(/forecast)返回的JSON根对象里,最关键的两个部分是:

  • list:一个JSON数组,包含每3小时的预报数据(总共40条,5天×8次/天)
  • city:包含目标城市的基本信息(名称、坐标等)

补全你的代码,实现数据解析

你已经写了请求的框架,现在只需要在onResponse方法里完成JSON解析逻辑。我把完整的解析代码补全并标注了注释:

public void find_forecast () { 
    String url = "http://api.openweathermap.org/data/2.5/forecast?id=4466033&appid=e4c641dd837c7947a127972091185dad&units=imperial"; 
    JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, 
        new Response.Listener<JSONObject>() { 
            @Override 
            public void onResponse(JSONObject response) { 
                try {
                    // 1. 获取所有3小时预报的数组
                    JSONArray forecastArray = response.getJSONArray("list");
                    
                    // 2. 遍历每一条预报数据
                    for(int i = 0; i < forecastArray.length(); i++){
                        JSONObject singleForecast = forecastArray.getJSONObject(i);
                        
                        // --- 提取时间信息 ---
                        long forecastTimeStamp = singleForecast.getLong("dt");
                        // 可选:把时间戳转成可读的日期格式,比如用SimpleDateFormat
                        
                        // --- 提取温度相关数据(在main对象内) ---
                        JSONObject mainData = singleForecast.getJSONObject("main");
                        double temp = mainData.getDouble("temp"); // 华氏度(因为你用了units=imperial)
                        double feelsLike = mainData.getDouble("feels_like");
                        int humidity = mainData.getInt("humidity");
                        
                        // --- 提取天气状况(在weather数组的第一个元素内) ---
                        JSONArray weatherArray = singleForecast.getJSONArray("weather");
                        JSONObject weatherInfo = weatherArray.getJSONObject(0);
                        String weatherDesc = weatherInfo.getString("description"); // 比如"light rain"
                        String weatherIcon = weatherInfo.getString("icon"); // 图标代码,用于加载天气图标
                        
                        // --- 提取其他可选数据(比如风速) ---
                        JSONObject windData = singleForecast.getJSONObject("wind");
                        double windSpeed = windData.getDouble("speed");
                        
                        // 这里可以把数据存到自定义的ForecastModel类,或者打印调试
                        Log.d("WeatherForecast", String.format("第%d条预报: 温度%.1f°F, 天气:%s", i+1, temp, weatherDesc));
                    }
                    
                    // 3. 提取城市信息(可选)
                    JSONObject cityInfo = response.getJSONObject("city");
                    String cityName = cityInfo.getString("name");
                    Log.d("WeatherForecast", "目标城市: " + cityName);
                    
                } catch (JSONException e) {
                    // 必须处理JSON解析异常,避免崩溃
                    e.printStackTrace();
                    Log.e("WeatherError", "JSON解析失败: " + e.getMessage());
                }
            } 
        }, 
        new Response.ErrorListener() { 
            @Override 
            public void onErrorResponse(VolleyError error) { 
                Log.e("WeatherError", "请求失败: " + error.getMessage());
            } 
        }
    );
    // 记得把请求加入Volley的请求队列
    // RequestQueue queue = Volley.newRequestQueue(this);
    // queue.add(jor);
}

关键注意点

  • 异常处理:JSON解析过程中一定要用try-catch包裹,因为如果API返回的结构和预期不符(比如字段名拼写错误),会抛出JSONException,直接导致崩溃。
  • 字段对应关系:要严格对应OpenWeatherMap API文档里的字段名,比如温度在main.temp,天气描述在weather[0].description,别写错字段名。
  • 单位问题:你用了units=imperial,所以温度是华氏度,如果要摄氏度可以改成units=metric。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:36:13