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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:00:46