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

如何通过Retrofit获取随机数API返回值并在项目中使用

解决Retrofit调用随机数API的返回值解析问题

问题根源

你调用的随机数API返回的是JSON数组格式(例如[123]),而非单个字符串或整数,直接用Call<String>会导致Gson解析失败,因为数据结构不匹配。

修正方案

1. 修改API接口的返回类型

将接口的返回类型改为Call<List<Integer>>,匹配API返回的数组结构:

import retrofit2.Call;
import retrofit2.http.GET;
import java.util.List;

public interface Api {
    @GET("random")
    Call<List<Integer>> getValues();
}

2. 调整主类的回调处理逻辑

在回调中解析数组,取出其中的随机数(该API默认返回单元素数组):

Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("https://www.randomnumberapi.com/api/v1.0/") // 注意baseUrl必须以/结尾
        .build();
Api api = retrofit.create(Api.class);

Call<List<Integer>> getNum = api.getValues();
getNum.enqueue(new Callback<List<Integer>>() {
    @Override
    public void onResponse(Call<List<Integer>> call, Response<List<Integer>> response) {
        if (!response.isSuccessful()) {
            textView.setText("code : " + response.code());
            return;
        }
        List<Integer> numberList = response.body();
        if (numberList != null && !numberList.isEmpty()) {
            int randomNumber = numberList.get(0);
            textView.setText(String.valueOf(randomNumber));
            // 此处可直接使用randomNumber(int类型)进行业务处理
        } else {
            textView.setText("未获取到有效随机数");
        }
    }

    @Override
    public void onFailure(Call<List<Integer>> call, Throwable t) {
        textView.setText(t.getMessage());
    }
});

额外注意点

  • Retrofit的baseUrl必须以/结尾,否则路径拼接会出现错误,确保你的baseUrl是https://www.randomnumberapi.com/api/v1.0/
  • 如果需要自定义返回结构,也可以创建一个包含单个整数字段的POJO类,但使用List<Integer>是最直接的方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:40:31