Android Java中如何将API GET请求返回的JSON转为数组?附报错解决
问题分析与解决方案
错误根源
你遇到的typeMismatch错误,核心原因是API返回的是JSON数组格式,但你误用了JsonObjectRequest发起请求。Volley的JsonObjectRequest会强制将响应解析为JSONObject,当实际返回的是JSON数组时,就会触发类型不匹配的异常。
具体修正步骤
1. 替换请求类为JsonArrayRequest
直接使用Volley专门处理JSON数组的JsonArrayRequest,匹配API返回格式,从根源解决解析错误。
2. 优化JSON解析逻辑
请求返回的直接是JSONArray,无需再手动转换,直接遍历数组即可。
3. 修复UI操作的冗余问题
- 不要在循环内重复调用
findViewById,提前在Activity的onCreate中初始化TextView,减少性能浪费。 - 循环内每次
setText会覆盖之前的内容,改用字符串拼接后一次性设置,才能显示所有数据。
修改后的完整代码
TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout_name); // 替换为你的布局文件名 textView = findViewById(R.id.text); // 发起JSON数组请求 JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, onewayUrl, null, response -> { StringBuilder allCareers = new StringBuilder(); try { for (int i = 0; i < response.length(); i++) { JSONObject item = response.getJSONObject(i); String career = item.getString("career"); allCareers.append(career).append("\n"); // 拼接所有职业内容 } textView.setText(allCareers.toString()); // 一次性设置到TextView } catch (JSONException e) { e.printStackTrace(); textView.setText("数据解析失败"); } }, error -> { error.printStackTrace(); textView.setText("请求API失败"); } ); // 设置重试策略 jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f)); Volley.newRequestQueue(AfterSearch.this).add(jsonArrayRequest); }
额外调试建议
如果不确定API返回的具体格式,可以在响应回调中添加日志打印,直观查看原始数据:
// 在JsonArrayRequest的response回调第一行添加 Log.d("API_RESPONSE", response.toString());
内容的提问来源于stack exchange,提问作者Kayes Fahim
相关产品推荐
相关产品推荐

