Home > Enterprise >  How to specify a different name for json key while using Retrofit Moshi
How to specify a different name for json key while using Retrofit Moshi

Time:08-29

I need to make a POST request to my backend with following json:

{
    start_time: 123456789
}

I have created the below data class for the body in Retrofit request:

data class MyRequestBody(
    @Json(name="start_time")
    val startTime: Long
)

But when I check on my backend the request contains the startTime field instead of start_time. How can I change the name of this variable for json serialization?

Edit: My build.gradle:

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-moshi:2.9.0"

My api interface:

internal interface RemoteTopicApi {

    @POST("xyz/")
    suspend fun getData(@Body body: MyRequestBody)

}

Retrofit Builder:

Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(MoshiConverterFactory.create())
    .build()

CodePudding user response:

1- Add those moshi dependencies:

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'    
// Moshi
implementation 'com.squareup.moshi:moshi-kotlin:1.13.0'
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.13.0'

2- Change Retrofit Builder to this:

Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(MoshiConverterFactory.create(
        Moshi.Builder()
            .addLast(KotlinJsonAdapterFactory())
            .build()
    ))
    .build()

This fixed the problem for me.

  • Related