
retrofit 默认支持“按需映射”——只需在数据类中声明需要的字段,gson 会自动忽略 json 中其他未声明的字段,无需额外配置。若出现解析错误,通常源于 gson 配置、空值处理或类型不匹配等问题。
在使用 Retrofit 进行 @GET 请求时,你完全不需要为响应 JSON 中的每一个字段都定义对应的 Kotlin 属性。正如你的用法所示:
data class ApiResponse(
val id: String,
)配合如下接口定义:
interface ApiService {
@GET("your/endpoint")
suspend fun apiCall(@Header("Authorization") authorization: String): Response
} ✅ 这是完全合法且推荐的做法——Gson(默认 Converter)会自动跳过 resourceUri、xxx、phone、email 等未声明字段,仅将 "id" 字段反序列化到 ApiResponse.id。
⚠️ 但若运行时报错(如 JsonParseException、NullPointerException 或 IllegalArgumentException),常见原因及解决方案如下:
✅ 1. 确保已正确添加 GsonConverterFactory
Retrofit 必须显式注册 Gson 转换器(尤其在自定义 OkHttpClient 或多模块项目中易被遗漏):
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create()) // ← 关键!不可省略
.build()✅ 2. 处理可能的 null 值(避免 String 类型接收 null)
你的示例中 xxx 字段可能为 null 或 [],但 ApiResponse 未包含它,这本身不会报错。但如果某必需字段(如 id)在某些响应中为 null,而你将其声明为非空 String,就会触发 JsonParseException。
✅ 推荐写法(安全适配空值):
data class ApiResponse(
val id: String?, // 允许 null
// 其他按需字段...
)或使用 @Nullable 注解(需启用 Gson 的 setLenient() 或 serializeNulls() —— 一般不推荐,优先用可空类型)。
✅ 3. 检查字段名与 JSON key 是否严格匹配(含大小写)
Gson 默认按字段名精确匹配。若服务端返回 "ID" 或 "Id",而你写的是 val id: String,则无法映射。此时需使用 @SerializedName:
data class ApiResponse(
@SerializedName("id")
val id: String?,
)✅ 4. 排查网络层或 Mock 干扰(如你示例中用了 Retromock)
你提供的代码片段中使用了 Retromock(非标准库),其 @MockResponse 若 JSON 格式非法(如逗号缺失、引号不闭合),会导致解析失败。请验证 mock body 是否为有效 JSON:
{"id":"22222","resourceUri":"ssss","xxx":null,"xxx":[],"phone":"kkk","email":"jjjjjj"}? 提示:该 JSON 中存在重复 key "xxx"(JSON 规范允许但 Gson 默认只取最后一个),建议服务端修复;若无法修改,可改用 Map + 手动提取,或自定义 TypeAdapter。
✅ 最小可运行示例(验证基础流程)
// 数据类(极简)
data class ApiResponse(val id: String?)
// 接口
interface ApiService {
@GET("test")
suspend fun fetchId(@Header("Authorization") token: String): Response
}
// 调用
val response = apiService.fetchId("Bearer abc123")
if (response.isSuccessful && response.body()?.id != null) {
println("Received ID: ${response.body()!!.id}")
} else {
println("Error: ${response.code()} ${response.message()}")
} ? 总结:你最初的实现思路完全正确。Retrofit + Gson 天然支持“忽略无关字段”。出错时,请优先检查:
- GsonConverterFactory 是否已添加;
- 必需字段是否可能为 null(改用可空类型);
- 字段命名是否与 JSON key 一致(注意大小写和下划线);
- Mock 或真实响应 JSON 是否语法合法、无歧义 key。
无需引入 @JsonIgnore、自定义解析器或复杂配置——简洁即强大。










