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

使用Retrofit调用Google Places API时response.body返回null求助

解决Retrofit调用Google Places API时的NullPointerException问题

我来帮你排查这个空指针问题——核心原因是你拿到的MainResponse对象为null,所以调用getResults()才会触发异常。下面是一步步的解决思路:

1. 先确认请求是否真的成功

别以为进入onResponse回调就代表请求没问题!Retrofit的response.isSuccessful()才是判断HTTP请求是否返回2xx成功状态的关键。如果这个方法返回false,response.body()肯定是null,错误信息藏在response.errorBody()里。

给你个示例代码,先把这层判断加上:

@Override
public void onResponse(Call<MainResponse> call, Response<MainResponse> response) {
    if (response.isSuccessful()) {
        // 到这里再处理返回的业务数据
        MainResponse mainResponse = response.body();
        if (mainResponse != null) {
            List<Result> results = mainResponse.getResults();
            // 正常处理结果逻辑
        } else {
            Log.e("MainActivity", "解析后MainResponse为空");
        }
    } else {
        // 处理请求失败的情况,比如打印错误信息
        try {
            String errorDetails = response.errorBody().string();
            Log.e("MainActivity", "请求失败: " + errorDetails);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 检查POJO类和API返回的JSON结构是否完全对齐

这是Retrofit解析失败最常见的原因——你之前不用Retrofit时能正常获取数据,说明API返回没问题,但Retrofit依赖Gson(或其他转换器)自动映射JSON到POJO类,只要结构有一点不匹配,就会解析失败返回null。

  • 核对字段名:比如JSON里的键是results,你的MainResponse类里不能写成result(大小写也得完全一致)。
  • 字段名不一致就加@SerializedName注解指定:
public class MainResponse {
    @SerializedName("results") // 明确对应JSON里的"results"键
    private List<Result> results;

    public List<Result> getResults() {
        return results;
    }
}
  • 还要检查嵌套对象(比如Result类)的子字段,有没有类型不匹配(比如把String写成int)或者遗漏字段的情况。

3. 确认Retrofit配置了正确的JSON转换器

如果你的Retrofit实例没加JSON转换器,根本没法解析返回的JSON,自然response.body()就是null。确保构建Retrofit时添加了Gson转换器:

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://maps.googleapis.com/maps/api/")
        .addConverterFactory(GsonConverterFactory.create()) // 必须加这个
        .build();

同时项目依赖里要包含Gson转换器的库:

implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // 版本号可根据实际调整

4. 打印完整响应内容排查问题

要是上面的步骤都没问题,建议你把API返回的原始内容打出来,看看是不是和你预期的JSON结构一致。可以给Retrofit加个日志拦截器:

先加依赖:

implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'

然后配置Retrofit:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // 打印完整请求响应

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(loggingInterceptor)
        .build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://maps.googleapis.com/maps/api/")
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

这样就能在Logcat里看到完整的请求参数和返回的JSON,方便你对比POJO类的结构是否正确。

5. 检查请求参数是否正确

虽然你不用Retrofit时正常,但用Retrofit构建请求时可能参数有误——比如API key是不是写错了、请求路径(比如place/nearbysearch/json)有没有拼写错误、参数名(比如location、radius)是否正确。参数错误会导致API返回错误JSON,而你的POJO是按成功响应写的,自然解析后就是null。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:15:43