Moshi Json name annotation property not working

102 views Asked by At

I'm trying to use @Json(name = "Result") property to change the field name and it's not working. The result is always null from retrofit response, but if I use the actual "Result" in the field it is working fine, here's the example data class.

Not Working:

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

Also Not working when using @field:Json(name = "Result")

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

Working:

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

Dependency: (Latest Moshi Version)

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

Network Call:

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

I also added moshi proguard.

2

There are 2 answers

1
Kamal Nayan On

Try using

val moshi =  Moshi
                .Builder()
                .add(KotlinJsonAdapterFactory())
                .build()



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

I fixed it by removing .addConverterFactory(GsonConverterFactory.create(gson)). It seems the Moshi and Gson Converter factory cannot be in the same builder.