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

Moshi @Json(name)注解属性失效问题求助

Moshi @Json注解不生效,Retrofit解析字段为null的解决方案

问题场景

尝试用Moshi的@Json(name = "Result")注解修改Kotlin数据类的字段名,无论直接使用@Json还是@field:Json,Retrofit解析后该字段始终返回null;但直接使用原字段名Result时,就能正常解析响应数据。

不生效的写法

@JsonClass(generateAdapter = true)
data class SMSResponse(
   @Json(name = "Result")
   val smsName: String?
)

同样不生效的写法

@JsonClass(generateAdapter = true)
data class SMSResponse(
   @field:Json(name = "Result")
   val smsName: String?
)

生效的写法

@JsonClass(generateAdapter = true)
data class SMSResponse(
   val Result: String?
)

当前依赖配置

implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
ksp("com.squareup.moshi:moshi-kotlin-codegen:1.15.0")

Retrofit构建代码

return Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(gson))
        .addConverterFactory(MoshiConverterFactory.create())
        .baseUrl(BuildConfig.BASE_URL)
        .client(okHttpClient)
        .build()

问题根源

核心问题出在Retrofit的ConverterFactory执行顺序:
你同时添加了GsonConverterFactory和MoshiConverterFactory,Retrofit会按照添加顺序优先使用第一个能处理响应体的转换器。这里Gson转换器先被加载,实际是Gson在解析你的响应数据,但Gson并不识别Moshi的@Json注解,无法完成字段映射,导致返回null;而直接使用Result字段名时,Gson默认按字段名大小写匹配,所以能正常解析。

另外,你的Moshi依赖版本不一致(moshi-kotlin为1.14.0,codegen为1.15.0),虽不是直接诱因,但可能引发其他潜在问题,建议统一版本。

解决方案

方案1:移除GsonConverterFactory,仅使用Moshi

如果项目不需要Gson作为转换器,直接删除Gson的ConverterFactory,确保Retrofit使用Moshi处理解析:

return Retrofit.Builder()
        .addConverterFactory(MoshiConverterFactory.create())
        .baseUrl(BuildConfig.BASE_URL)
        .client(okHttpClient)
        .build()

同时统一Moshi依赖版本,例如都使用1.15.0:

implementation("com.squareup.moshi:moshi-kotlin:1.15.0")
ksp("com.squareup.moshi:moshi-kotlin-codegen:1.15.0")

方案2:保留Gson,改用Gson的注解

如果必须保留GsonConverterFactory,需使用Gson对应的字段映射注解@SerializedName替代Moshi的@Json:

data class SMSResponse(
   @SerializedName("Result")
   val smsName: String?
)

这种情况下@JsonClass注解可以移除,因为Gson不需要该注解生成适配器。

方案3:调整ConverterFactory顺序(不推荐)

如果一定要同时保留两个转换器,且希望优先使用Moshi,可以将MoshiConverterFactory放在GsonConverterFactory前面:

return Retrofit.Builder()
        .addConverterFactory(MoshiConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson))
        .baseUrl(BuildConfig.BASE_URL)
        .client(okHttpClient)
        .build()

但这种做法容易混淆不同转换器的适用场景,除非有明确业务需求,否则不建议使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:00:16