4

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()
Arpit Shukla
  • 9,612
  • 1
  • 14
  • 40

1 Answers1

2

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.

Mohamed Rejeb
  • 2,281
  • 1
  • 7
  • 16
  • It worked. Thanks! So, does this mean that the `@Json` annotation is useless without all this setup? – Arpit Shukla Aug 28 '22 at 14:16
  • Well yes, this is the import for @Json `import com.squareup.moshi.Json`so it's part of `com.squareup.moshi:moshi-kotlin` so without this dependency it's useless. `com.squareup.retrofit2:converter-moshi` doesn't contain all moshi features it's just used to link moshi with retrofit. – Mohamed Rejeb Aug 28 '22 at 14:26
  • @ArpitShukla Kotlin's property doesn't see the annotation. You could do `@property:Json(...)`, but using the codegen is better, anyway. – Eric Cochran Aug 29 '22 at 09:19