You need to enable JavaScript to run this app. Android开发中Volley请求出现JSONArray无法转JSONObject报错问题
优惠活动
大模型
产品
解决方案
定价
更多

Android开发中Volley请求出现JSONArray无法转JSONObject报错问题

Volley 类型转换报错:JSONArray 无法转换为 JSONObject

问题表现

持续收到JSONArray无法转换为JSONObject的报错,待解析的接口返回本身就是JSON对象数组格式,仍然触发报错,附上相关代码、布局文件和接口返回数据如下。


原有Java业务代码

public class DetailActivity extends AppCompatActivity {

    ImageView imageView;
    TextView options, bio, noBio;
    private final String JSON_URL = "https://run.mocky.io/v3/987b97bd-6895-40d1-9d37-ce404162c491";
    private JsonObjectRequest jsonObjectRequest;
    private RequestQueue requestQueue;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        imageView = (ImageView) findViewById(R.id.iv_image);
        options = (TextView) findViewById(R.id.tv_options);
        bio = (TextView) findViewById(R.id.tv_bio);
        noBio = (TextView) findViewById(R.id.tv_no_bio);

        getDetails();
    }

    private void getDetails() {
        jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSON_URL, null ,
            new Response.Listener<JSONObject>() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = new JSONArray(response.toString());
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String type = jsonObject.getString("type");
                            boolean isVisible = jsonObject.getBoolean("isVisible");

                            if (!isVisible) {
                                imageView.setVisibility(View.GONE);
                                options.setText("API response is false. So data will not be shown.");
                                bio.setText("API response is false. So data will not be shown.");
                            } else {
                                imageView.setVisibility(View.VISIBLE);
                                options.setVisibility(View.VISIBLE);
                                bio.setVisibility(View.VISIBLE);

                                Intent intent = getIntent();
                                Glide.with(getApplicationContext()).load((Bitmap) intent.getParcelableExtra("image")).into(imageView);
                                options.setText("Choosen Option : " + getIntent().getStringExtra("options"));
                                String str_bio = getIntent().getStringExtra("comments");
                                if (str_bio == null) {
                                    bio.setVisibility(View.GONE);
                                    noBio.setVisibility(View.VISIBLE);
                                } else {
                                    bio.setText("Bio : " + str_bio);
                                    noBio.setVisibility(View.GONE);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        Toast.makeText(DetailActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("Exception", e.getMessage());
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(DetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                    Log.d("Error", error.getMessage());
                }
            });
        requestQueue = Volley.newRequestQueue(DetailActivity.this);
        requestQueue.add(jsonObjectRequest);
    }
}

对应的XML布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F0E6FD"
    android:orientation="vertical"
    tools:context=".DetailActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp">

        <ImageView
            android:id="@+id/iv_image"
            android:layout_width="250dp"
            android:layout_height="250dp"
            android:layout_gravity="center"
            android:scaleType="fitXY"/>

        <TextView
            android:id="@+id/tv_options"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Choosen option : "
            android:textSize="17dp"
            android:fontFamily="@font/notoserif_bold"
            android:layout_marginTop="15dp"
            android:textColor="@color/black"/>

        <TextView
            android:id="@+id/tv_bio"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Bio :"
            android:textSize="17dp"
            android:fontFamily="@font/notoserif_bold"
            android:layout_marginTop="15dp"
            android:textColor="@color/black"/>

        <TextView
            android:id="@+id/tv_no_bio"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="No Bio provided"
            android:gravity="center"
            android:textSize="15dp"
            android:fontFamily="@font/notoserif_regular"
            android:layout_marginTop="15dp"
            android:textColor="@color/black"/>
    </LinearLayout>
</LinearLayout>

接口返回的示例JSON数据

[
   {
      "type":"PHOTO",
      "isVisible":true
   },
   {
      "type":"SINGLE_CHOICE",
      "isVisible":true
   },
   {
      "type":"COMMENT",
      "isVisible":true
   }
]

报错根源与修复方案

报错触发点在Volley的请求解析阶段:JsonObjectRequest的内置逻辑会强制将接口响应体解析为JSONObject类型,当接口返回的是JSONArray结构时,解析流程就会直接抛出类型转换异常,根本不会执行到你代码里手动将JSONObject转JSONArray的逻辑。

修复方案(推荐)

直接将请求类型从JsonObjectRequest替换为Volley内置的JsonArrayRequest,该类会自动将响应解析为JSONArray格式,不需要手动做类型转换。

修改后的核心getDetails方法如下:

private void getDetails() {
    // 替换为JsonArrayRequest,泛型对应JSONArray
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
        Request.Method.GET, 
        JSON_URL, 
        null,
        new Response.Listener<JSONArray>() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onResponse(JSONArray jsonArray) {
                try {
                    // 删掉原来手动new JSONArray的逻辑,直接用回调返回的jsonArray
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String type = jsonObject.getString("type");
                        boolean isVisible = jsonObject.getBoolean("isVisible");

                        if (!isVisible) {
                            imageView.setVisibility(View.GONE);
                            options.setText("API response is false. So data will not be shown.");
                            bio.setText("API response is false. So data will not be shown.");
                        } else {
                            imageView.setVisibility(View.VISIBLE);
                            options.setVisibility(View.VISIBLE);
                            bio.setVisibility(View.VISIBLE);

                            Intent intent = getIntent();
                            Glide.with(getApplicationContext())
                                .load((Bitmap) intent.getParcelableExtra("image"))
                                .into(imageView);
                            options.setText("Choosen Option : " + getIntent().getStringExtra("options"));
                            String str_bio = getIntent().getStringExtra("comments");
                            if (str_bio == null) {
                                bio.setVisibility(View.GONE);
                                noBio.setVisibility(View.VISIBLE);
                            } else {
                                bio.setText("Bio : " + str_bio);
                                noBio.setVisibility(View.GONE);
                            }
                        }
                    }
                } catch (JSONException e) {
                    Toast.makeText(DetailActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    Log.d("Exception", e.getMessage());
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("Error", error.getMessage());
            }
        });

    requestQueue = Volley.newRequestQueue(DetailActivity.this);
    requestQueue.add(jsonArrayRequest);
}

同时需要将原来定义的private JsonObjectRequest jsonObjectRequest;成员变量替换为private JsonArrayRequest jsonArrayRequest;,避免类名不匹配的编译错误。


内容的提问来源于stack exchange,提问作者Pranav Kumar K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 17:15:02