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

Retrofit单@Body参数POST请求报错找不到第2个参数注解如何解决

问题原因

你的报错核心是低版本Retrofit无法识别Kotlin suspend函数的自动生成参数:
Kotlin的suspend函数在编译为字节码时,会自动在参数列表末尾追加一个Continuation类型的参数,作为协程挂起恢复的载体。你定义的registerDeviceAsync虽然看起来只有1个参数,但字节码层面实际有2个参数:你显式声明的model、系统自动追加的Continuation参数。
如果你的Retrofit版本低于2.6.0,官方还没有原生支持suspend函数,会把这个自动生成的Continuation当成你需要声明注解的业务参数,所以抛出No annotation found for param 2的异常。
还有一种概率较低的触发场景:你开启了代码混淆,但没有配置Retrofit、Kotlin协程相关的保留规则,导致Retrofit无法识别suspend函数的元数据,也会误判参数数量。

解决方案

  • 优先升级Retrofit版本到2.6.0及以上的稳定版,2.6.0+版本原生支持suspend函数,会自动忽略末尾的Continuation参数,不需要额外配置:
// 示例配置,替换为最新稳定版即可
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
  • 如果你因项目限制无法升级Retrofit版本,需要额外添加协程Call适配器依赖,并在构造Retrofit实例时注册适配器:
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'

修改你的Retrofit构造代码:

fun createService(): IRetrofitCommService {
    return Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        // 新增协程Call适配器注册
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()
        .create(IRetrofitCommService::class.java)
}
  • 检查混淆配置文件(proguard-rules.pro),添加Retrofit、Kotlin相关的保留规则:
# Retrofit 规则
-keep class retrofit2.** { *; }
-keepattributes Signature, Exceptions, Annotation, RuntimeVisibleAnnotations
# 保留kotlin协程元数据
-keep class kotlin.coroutines.** { *; }
# 保留你的DTO类不被混淆,替换为实际的DTO包路径
-keep class com.example.xxx.dto.** { *; }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:39:02