Law

Raw JSON body in Retrofit

Raw JSON body in Retrofit

To send a raw JSON body in String format in Retrofit, I found out I need to include scalar library.

scalar = { module = "com.squareup.retrofit2:converter-scalars", version.ref = "retrofit" }

In my ApiHelper class.

import retrofit2.converter.scalars.ScalarsConverterFactory

object ApiHelper {
	fun getInstance(): Retrofit =  
    Retrofit  
        .Builder()  
        .baseUrl(baseApi)  
        .addConverterFactory(ScalarsConverterFactory.create())  
        .addConverterFactory(  
            json.asConverterFactory(contentType),  
        )  
        .client(client)  
        .build()
}

Important stuff to take note is that, ScalarsConverterFactory.create() needs to be called first before the convert factory, or else it won't work.

So, sending a raw @Body should now work.

@PATCH("profile")  
suspend fun updateUserProfile(  
    @Header("Authorization") accessToken: String,  
    @Body body: String  
): Response<Unit>