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

Android使用OkHttp请求接口后解析JSON提取指定字段求助

修改方案

你只需要补全JSON对象的字段提取逻辑,调整TextView的赋值内容即可,修改后的完整代码如下:

textView = findViewById(R.id.textVieww);
String url = "https://zenquotes.io/api/random";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url(url)
        .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
        // 也可以在这里自定义请求失败的提示文案
        Quote.this.runOnUiThread(() ->
                textView.setText("网络请求失败,请稍后重试"));
    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            final String myResponse = response.body().string();
            String showText = "内容解析失败";
            try {
                JSONArray jsonarray = new JSONArray(myResponse);
                for(int i=0; i<jsonarray.length(); i++) {
                    JSONObject obj = jsonarray.getJSONObject(i);
                    // 提取q和a字段,optString第二个参数是字段不存在时的默认值,避免异常崩溃
                    String quote = obj.optString("q", "暂无名言内容");
                    String author = obj.optString("a", "佚名");
                    // 可自行调整展示文本的拼接格式,这里默认是内容+换行+作者的格式
                    showText = quote + "\n\n—— " + author;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 设置最终拼接好的展示内容
            String finalShowText = showText;
            Quote.this.runOnUiThread(() ->
                    textView.setText(finalShowText));
        }
    }
});
}

核心修改说明:

  • 用optString替代getString提取字段,容错性更高,不会因为字段缺失直接崩溃
  • 可根据UI设计需求自定义拼接格式,比如给名言加引号、调整缩进和符号等
  • 补充了请求失败场景的提示逻辑,优化用户体验

内容的提问来源于stack exchange,提问作者Tyler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 08:06:04