如何在Java中访问OpenWeatherMap返回JSON中的数组?
解决OpenWeatherMap API中weather数组的访问问题
你的问题出在数组访问方式上——getJSONArray("weather[0]")是错误写法,getJSONArray方法只需要传入数组对应的键名weather,之后再通过索引获取数组里的具体元素。
正确操作逻辑
OpenWeatherMap返回的weather字段是一个JSON数组,每个元素是包含天气详情的JSONObject,你需要:
- 从响应中获取
weather数组 - 取出数组的第一个元素(天气接口通常仅返回一组当前天气数据)
- 从该元素中提取所需字段,比如天气类型、详细描述、图标ID等
修改后的完整代码
同时优化了重复获取main对象的冗余操作:
public void getWeather(View view) { String apiKey="40bb658a709ebb7b1c210655e7f5cfe6"; String city=et.getText().toString(); String url="https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=40bb658a709ebb7b1c210655e7f5cfe6&units=metric"; RequestQueue queue= Volley.newRequestQueue(getApplicationContext()); JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { // 获取国家信息 JSONObject sysObj = response.getJSONObject("sys"); String country = sysObj.getString("country"); tvcountry.setText(country); // 优化:仅获取一次main对象,避免重复调用 JSONObject mainObj = response.getJSONObject("main"); String temperature = mainObj.getString("temp"); tvTemp.setText("Current: " + temperature + " C"); String feelsLike = mainObj.getString("feels_like"); tvFeels_Like.setText("Feels like: " + feelsLike + " C"); String maxtemp = mainObj.getString("temp_max"); tvMaxTemp.setText("Max: " + maxtemp + " C"); String mintemp = mainObj.getString("temp_min"); tvMinTemp.setText("Min: " + mintemp + " C"); // 正确获取weather数组及其中的元素 JSONArray weatherArray = response.getJSONArray("weather"); // 取数组第一个元素(当前天气) if (weatherArray.length() > 0) { JSONObject weatherObj = weatherArray.getJSONObject(0); // 提取天气主类型(如Rain、Sunny) String weatherMain = weatherObj.getString("main"); // 提取天气详细描述(如light rain) String weatherDesc = weatherObj.getString("description"); // 提取天气图标ID(用于展示对应图标) String weatherIcon = weatherObj.getString("icon"); // 将天气信息设置到对应TextView(示例) tvWeather.setText("Weather: " + weatherMain); tvWeatherDesc.setText("Description: " + weatherDesc); } } catch (JSONException e) { Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(SecondPage.this, error.toString(), Toast.LENGTH_SHORT).show(); } }); queue.add(request); }
补充说明
- 若要展示天气图标,可通过OpenWeatherMap的图标URL拼接实现:
https://openweathermap.org/img/wn/[iconId]@2x.png,比如weatherIcon为"01d"时,完整URL为https://openweathermap.org/img/wn/01d@2x.png - 添加了数组长度判断,避免空数组导致的异常
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

