
retrofit 默认支持“字段忽略”——只需在数据类中声明所需字段,gson 会自动跳过 json 中未定义的字段,无需额外配置。本文详解正确实现方式、常见报错原因及最佳实践。
在使用 Retrofit 进行 @GET 请求时,若后端返回的 JSON 包含大量字段(如 resourceUri、phone、email 等),而你仅需其中少数几个(例如仅 id),完全不需要定义全部字段。Retrofit + Gson 的默认行为正是「宽松反序列化」:只要目标数据类中声明了对应字段(类型兼容),其余未知字段会被自动忽略,不会抛出异常。
✅ 正确做法如下:
-
精简定义数据类(仅含所需字段):
data class ApiResponse( val id: String )
即使响应中包含 "xxx": null、"phone": "kkk" 等未声明字段,Gson 也会静默跳过,不会报错。
-
确保 Retrofit 配置了 GsonConverterFactory(关键!):
val retrofit = Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) // 必须添加! .build()⚠️ 若遗漏此行,或使用了其他不兼容的 Converter(如 Moshi、Jackson 但未正确配置),将导致解析失败。
-
接口方法保持简洁:
interface ApiService { @GET("user/profile") suspend fun apiCall(@Header("Authorization") authorization: String): Response}
? 常见报错原因排查:
- ❌ JsonParseException / Expected BEGIN_OBJECT but was STRING:说明响应不是合法 JSON,或服务器返回了 HTML 错误页(如 401/500 页面);
- ❌ NullPointerException 在访问 response.body():检查是否调用 response.isSuccessful,且 response.body() 不为 null;
- ❌ IllegalArgumentException: Unable to create converter:确认 GsonConverterFactory 已添加,且 gson 依赖已引入(如 com.squareup.retrofit2:converter-gson:2.9.0);
- ❌ 字段名不匹配:JSON 中是 "id",Kotlin 中写成 val ID: String(大小写敏感),可加 @SerializedName("id") 显式映射:
data class ApiResponse( @SerializedName("id") val id: String )
? 进阶建议:
- 如需更严格控制(如禁止未知字段),可自定义 Gson 实例:
val gson = GsonBuilder() .setLenient() // 允许 JSON 格式松散(如末尾逗号) .create() Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(gson)) - 对于空值字段(如 "xxx": null 或 "xxx": []),只要数据类中未声明该字段,Gson 完全无视;若声明了但类型不匹配(如声明 val xxx: String 却收到 null),则需改用可空类型 val xxx: String? —— 但本例中无需声明,故无需处理。
总结:你的原始实现逻辑完全正确。问题大概率出在 Retrofit 初始化缺失 Gson Converter、网络响应非预期格式,或混淆了 Response










