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

Kotlin序列化Retrofit接口返回值为null问题求助

问题分析与解决方案

可能的原因及对应解决办法

1. Retrofit未配置Kotlin Serialization转换器

如果NetworkModule里没给Retrofit添加Kotlin Serialization转换器,JSON无法正确映射到模型类,会导致字段为null。

解决步骤:

  • 先确认添加了必要依赖(Module级build.gradle.kts):
dependencies {
    implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
}
  • 在NetworkModule中配置Retrofit时加入转换器:
val json = Json {
    ignoreUnknownKeys = true // 忽略JSON中未定义的字段,避免解析失败
}

val retrofit = Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
    .build()

2. 泛型类型信息丢失(类型擦除)

Kotlin泛型运行时会被擦除,Retrofit默认无法解析嵌套泛型模型,需确保序列化器能识别泛型类型。

解决办法:

  • 保持之前的泛型模型结构,同时在Retrofit配置中使用支持泛型的Json实例(如上一步的json配置),开启ignoreUnknownKeys避免因字段不匹配导致解析中断。
  • 若仍有问题,可在接口调用时通过serializer()显式指定泛型类型(不过多数情况下,正确配置转换器即可解决)。

3. 模型类序列化注解不完整

  • 检查Info、Element类是否都添加了@Serializable注解,缺少注解会导致对应字段解析失败,进而整个response为null。
  • 确认JSON字段名和模型字段名完全匹配,若存在大小写或命名差异,需添加@SerialName注解:
@Serializable
data class APINetworkResponse<T>(
    @SerialName("response")
    val response: Response<T>
)

4. 依赖版本不兼容

确保Retrofit、Kotlin Serialization转换器、kotlinx-serialization-json的版本相互兼容。比如Retrofit 2.9.0对应转换器1.0.0,kotlinx-serialization-json 1.6.0适配Kotlin 1.8+版本(根据项目Kotlin版本调整)。

验证步骤

  1. 开启Retrofit日志拦截器,确认返回的JSON格式和模型完全匹配:
val loggingInterceptor = HttpLoggingInterceptor().apply {
    level = HttpLoggingInterceptor.Level.BODY
}

val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(loggingInterceptor)
    .build()

val retrofit = Retrofit.Builder()
    .client(okHttpClient)
    // ...其他配置
    .build()
  1. 先测试非泛型模型解析,排除泛型问题:
@Serializable
data class ElementResponse(
    val response: ElementInnerResponse
)

@Serializable
data class ElementInnerResponse(
    val info: Info,
    val body: Element
)

// 接口临时修改为
suspend fun getElements(): ElementResponse

如果这个能正常解析,说明问题出在泛型处理上,回到第二步调整配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:01:15