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

Android使用kotlinx serialization无法获取数据的问题求助

使用Kotlinx Serialization作为Retrofit转换器无法解析GitHub仓库JSON数组的解决方案

以下是针对你遇到问题的排查方向和修复方案:

1. 修复OkHttpClient重复添加拦截器的问题

你的代码中okHttpBuilder是全局变量,每次调用provideApiService()都会重复添加BasicAuthInterceptor,可能导致请求异常。需改为每次创建独立的OkHttpClient实例:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {
    @Provides
    fun providesBaseUrl(): String = "https://api.github.com"
    
    private val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }
    
    @Provides
    fun provideApiService(): ApiService {
        // 每次创建新的OkHttpClient Builder,避免重复添加拦截器
        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .addInterceptor(BasicAuthInterceptor())
            .build()
            
        val contentType = "application/json".toMediaType()
        return Retrofit.Builder()
            .baseUrl(providesBaseUrl())
            .addConverterFactory(Json.asConverterFactory(contentType))
            .client(okHttpClient)
            .build()
            .create(ApiService::class.java)
    }
    ...
}

2. 配置Kotlinx Serialization的Json实例适配GitHub响应

GitHub的API响应可能包含数据类中未定义的额外字段,默认的Json实例会因无法识别这些字段而解析失败,需开启忽略未知键的配置:

// 在provideApiService中替换默认Json实例
val json = Json {
    ignoreUnknownKeys = true // 忽略数据类未定义的JSON字段
    coerceInputValues = true // 自动转换不匹配的输入类型(如null转默认值)
}

// 使用配置后的Json创建转换器
.addConverterFactory(json.asConverterFactory(contentType))

3. 检查数据类的序列化注解

确保你的仓库数据类添加了@Serializable注解,且字段与JSON键名匹配(键名不一致时需用@SerialName指定):

@Serializable
data class GithubRepo(
    @SerialName("id") val id: Long,
    @SerialName("name") val repoName: String, // 示例:字段名与JSON键名不同时用@SerialName
    @SerialName("full_name") val fullName: String
    // 其他需要的字段...
)

4. 确认ApiService接口返回类型正确

确保接口方法的返回类型是对应JSON数组的List<GithubRepo>,而非单个对象:

interface ApiService {
    @GET("user/repos") // 示例接口路径
    suspend fun getUserRepos(): List<GithubRepo>
}

5. 核对依赖配置

确认项目中已正确添加Kotlinx Serialization相关依赖:

  • 项目级build.gradle添加插件:
plugins {
    id 'org.jetbrains.kotlin.plugin.serialization' version '你的Kotlin版本号'
}
  • 模块级build.gradle添加依赖:
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0"
implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0"

内容的提问来源于stack exchange,提问作者Влад Михнёнок

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:40:25