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

Android启用minifyEnabled true时Retrofit无法接收数据求助

解决方案:minifyEnabled=true 下 Retrofit+Gson 解析字段全为 null 问题

1. 统一 Retrofit 与 Gson Converter 版本

你当前使用的 retrofit:2.6.0 和 converter-gson:2.5.0 版本不一致,可能存在兼容性问题(尤其是协程 suspend 方法的处理)。将依赖统一为同版本:

com.squareup.retrofit2:retrofit:2.6.0
com.squareup.retrofit2:converter-gson:2.6.0
com.squareup.okhttp3:logging-interceptor:3.12.0

2. 修正混淆规则

原规则未明确保留实体类的构造方法,Gson 反射创建实例时会失败,导致字段解析为 null。替换为以下精准规则:

# Gson 核心规则
-keepattributes Signature
-keepattributes *Annotation*
-dontwarn sun.misc.**
-keep class com.google.gson.stream.** { *; }

# 保留带 @SerializedName 注解的字段,以及类的所有构造方法
-keepclassmembers class * {
    @com.google.gson.annotations.SerializedName <fields>;
    <init>(...);
}

# 明确保留你的实体类(替换为实际的包路径)
-keep class com.yourapp.model.BaseRequest { *; }
-keep class com.yourapp.model.BaseResponse { *; }

# Retrofit 规则
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Exceptions
-keepattributes EnclosingMethod

# 保留 Retrofit 接口定义
-keepclasseswithmembers interface * {
    @retrofit2.http.* <methods>;
}
  • 保留构造方法:Gson 依赖反射创建实体类实例,混淆会移除未直接调用的构造方法,导致解析失败。
  • 明确指定实体类:避免包名匹配遗漏,确保核心数据类不被混淆或裁剪。

3. 验证混淆结果

通过 Android Studio 的 Build -> Analyze APK 功能,查看混淆后的 BaseRequest 和 BaseResponse 类,确认以下内容:

  • 字段名未被重命名
  • @SerializedName 注解仍存在
  • 构造方法未被移除

4. 排查响应体格式

启用 OkHttp 日志拦截器,打印完整的服务器响应体,确认返回的 JSON 格式与 @SerializedName 注解的字段名完全匹配:

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
    .build();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 11:18:12