Android Studio中JsonArrayRequest无法获取OpenWeatherMap API数据
问题原因
你用JsonArrayRequest请求失败的核心原因是:OpenWeatherMap API返回的是JSON对象(外层用{}包裹),但JsonArrayRequest只能解析外层是[]的JSON数组,解析时会触发格式错误,进而调用onErrorResponse。而StringRequest仅直接获取响应字符串,不做JSON格式校验,所以能正常返回数据。
修复方案
把JsonArrayRequest替换为JsonObjectRequest,同时调整响应监听器为Response.Listener<JSONObject>,修改后的代码如下:
btn_cityID.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); String apikey = "//"; String url = "//"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show(); // 可进一步解析JSON字段,示例:获取天气信息数组 // try { // JSONArray weatherArray = response.getJSONArray("weather"); // JSONObject weatherItem = weatherArray.getJSONObject(0); // String weatherMain = weatherItem.getString("main"); // // 处理解析后的数据 // } catch (JSONException e) { // e.printStackTrace(); // } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, "Unable to fetch data: " + error.getMessage(), Toast.LENGTH_SHORT).show(); } }); queue.add(request); } });
额外提示
- 在
onErrorResponse中添加error.getMessage(),可以打印具体错误信息,更方便排查问题 - 解析JSON时务必捕获
JSONException异常,避免程序崩溃
内容的提问来源于stack exchange,提问作者Ledeni
相关产品推荐
相关产品推荐

